




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference




class 		__A   (      UpperCamelCase__       ,    unittest.TestCase      ):
						UpperCamelCase      =       ShapEPipeline
						UpperCamelCase      =       ["""prompt"""]
						UpperCamelCase      =       ["""prompt"""]
						UpperCamelCase      =       [
						    """num_images_per_prompt""",
						    """num_inference_steps""",
						    """generator""",
						    """latents""",
						    """guidance_scale""",
						    """frame_size""",
						    """output_type""",
						    """return_dict""",
						]
						UpperCamelCase      =       False

						@property
						def      A__    (		self :Dict			):
										'''simple docstring'''

										return 32

						@property
						def      A__    (		self :Optional[Any]			):
										'''simple docstring'''

										return 32

						@property
						def      A__    (		self :Any			):
										'''simple docstring'''

										return self.time_input_dim * 4

						@property
						def      A__    (		self :Optional[int]			):
										'''simple docstring'''

										return 8

						@property
						def      A__    (		self :Any			):
										'''simple docstring'''

										__magic_name__						:						Any										=CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
										return tokenizer

						@property
						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										torch.manual_seed(0			)
										__magic_name__						:						Any										=CLIPTextConfig(
										    bos_token_id=0     ,			eos_token_id=2     ,			hidden_size=self.text_embedder_hidden_size     ,			projection_dim=self.text_embedder_hidden_size     ,			intermediate_size=37     ,			layer_norm_eps=1E-05     ,			num_attention_heads=4     ,			num_hidden_layers=5     ,			pad_token_id=1     ,			vocab_size=10_00     ,			)
										return CLIPTextModelWithProjection(__snake_case			)

						@property
						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										torch.manual_seed(0			)

										__magic_name__						:						Union[str, Any]										={
										    """num_attention_heads""": 2,
										    """attention_head_dim""": 16,
										    """embedding_dim""": self.time_input_dim,
										    """num_embeddings""": 32,
										    """embedding_proj_dim""": self.text_embedder_hidden_size,
										    """time_embed_dim""": self.time_embed_dim,
										    """num_layers""": 1,
										    """clip_embed_dim""": self.time_input_dim * 2,
										    """additional_embeddings""": 0,
										    """time_embed_act_fn""": """gelu""",
										    """norm_in_type""": """layer""",
										    """encoder_hid_proj_type""": None,
										    """added_emb_type""": None,
										}

										__magic_name__						:						Optional[Any]										=PriorTransformer(**__snake_case			)
										return model

						@property
						def      A__    (		self :int			):
										'''simple docstring'''

										torch.manual_seed(0			)

										__magic_name__						:						Optional[int]										={
										    """param_shapes""": (
										        (self.renderer_dim, 93),
										        (self.renderer_dim, 8),
										        (self.renderer_dim, 8),
										        (self.renderer_dim, 8),
										    ),
										    """d_latent""": self.time_input_dim,
										    """d_hidden""": self.renderer_dim,
										    """n_output""": 12,
										    """background""": (
										        0.1,
										        0.1,
										        0.1,
										    ),
										}
										__magic_name__						:						Any										=ShapERenderer(**__snake_case			)
										return model

						def      A__    (		self :Dict			):
										'''simple docstring'''

										__magic_name__						:						List[str]										=self.dummy_prior
										__magic_name__						:						str										=self.dummy_text_encoder
										__magic_name__						:						Dict										=self.dummy_tokenizer
										__magic_name__						:						Union[str, Any]										=self.dummy_renderer

										__magic_name__						:						List[str]										=HeunDiscreteScheduler(
										    beta_schedule="""exp"""     ,			num_train_timesteps=10_24     ,			prediction_type="""sample"""     ,			use_karras_sigmas=__snake_case     ,			clip_sample=__snake_case     ,			clip_sample_range=1.0     ,			)
										__magic_name__						:						Union[str, Any]										={
										    """prior""": prior,
										    """text_encoder""": text_encoder,
										    """tokenizer""": tokenizer,
										    """renderer""": renderer,
										    """scheduler""": scheduler,
										}

										return components

						def      A__    (		self :Any     ,			__snake_case :Optional[Any]     ,			__snake_case :Optional[int]=0			):
										'''simple docstring'''

										if str(__snake_case			).startswith("""mps"""			):
														__magic_name__						:						Union[str, Any]										=torch.manual_seed(__snake_case			)
										else:
														__magic_name__						:						List[Any]										=torch.Generator(device=__snake_case			).manual_seed(__snake_case			)
										__magic_name__						:						str										={
										    """prompt""": """horse""",
										    """generator""": generator,
										    """num_inference_steps""": 1,
										    """frame_size""": 32,
										    """output_type""": """np""",
										}
										return inputs

						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										__magic_name__						:						str										="""cpu"""

										__magic_name__						:						str										=self.get_dummy_components()

										__magic_name__						:						Optional[int]										=self.pipeline_class(**__snake_case			)
										__magic_name__						:						Dict										=pipe.to(__snake_case			)

										pipe.set_progress_bar_config(disable=__snake_case			)

										__magic_name__						:						str										=pipe(**self.get_dummy_inputs(__snake_case			)			)
										__magic_name__						:						Dict										=output.images[0]
										__magic_name__						:						str										=image[0, -3:, -3:, -1]

										assert image.shape == (20, 32, 32, 3)

										__magic_name__						:						Union[str, Any]										=np.array(
										    [
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										        0.00039216,
										    ]			)

										assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2

						def      A__    (		self :Optional[int]			):
										'''simple docstring'''

										self._test_inference_batch_consistent(batch_sizes=[1, 2]			)

						def      A__    (		self :List[str]			):
										'''simple docstring'''

										__magic_name__						:						Optional[int]										=torch_device == """cpu"""
										__magic_name__						:						Optional[int]										=True

										self._test_inference_batch_single_identical(
										    batch_size=2     ,			test_max_difference=__snake_case     ,			relax_max_difference=__snake_case     ,			)


						def      A__    (		self :List[str]			):
										'''simple docstring'''

										__magic_name__						:						int										=self.get_dummy_components()
										__magic_name__						:						List[Any]										=self.pipeline_class(**__snake_case			)
										__magic_name__						:						int										=pipe.to(__snake_case			)
										pipe.set_progress_bar_config(disable=__snake_case			)

										__magic_name__						:						List[Any]										=1
										__magic_name__						:						Optional[int]										=2

										__magic_name__						:						Any										=self.get_dummy_inputs(__snake_case			)

										for key in inputs.keys():
														if key in self.batch_params:
																		__magic_name__						:						List[str]										=batch_size * [inputs[key]]

										__magic_name__						:						List[str]										=pipe(**__snake_case     ,			num_images_per_prompt=__snake_case			)[0]

										assert images.shape[0] == batch_size * num_images_per_prompt




@slow
@require_torch_gpu
class 		__A   (      unittest.TestCase      ):

						def      A__    (		self :str			):
										'''simple docstring'''

										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()


						def      A__    (		self :Optional[Any]			):
										'''simple docstring'''

										__magic_name__						:						Any										=load_numpy(
										    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
										    """/shap_e/test_shap_e_np_out.npy"""			)
										__magic_name__						:						List[Any]										=ShapEPipeline.from_pretrained("""openai/shap-e"""			)
										__magic_name__						:						str										=pipe.to(__snake_case			)
										pipe.set_progress_bar_config(disable=__snake_case			)

										__magic_name__						:						int										=torch.Generator(device=__snake_case			).manual_seed(0			)

										__magic_name__						:						List[Any]										=pipe(
										    """a shark"""     ,			generator=__snake_case     ,			guidance_scale=15.0     ,			num_inference_steps=64     ,			frame_size=64     ,			output_type="""np"""     ,			).images[0]

										assert images.shape == (20, 64, 64, 3)

										assert_mean_pixel_difference(__snake_case     ,			__snake_case			)










import math

import tensorflow as tf
from packaging import version




def 		lowerCAmelCase_ (						lowerCamelCase ):
				__magic_name__						:						str										=tf.convert_to_tensor(lowerCamelCase )
				__magic_name__						:						List[str]										=0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 )						,  x.dtype ) ))

				return x * cdf




def 		lowerCAmelCase_ (						lowerCamelCase ):
				__magic_name__						:						str										=tf.convert_to_tensor(lowerCamelCase )
				__magic_name__						:						Optional[Any]										=tf.cast(math.pi						,  x.dtype )
				__magic_name__						:						int										=tf.cast(0.0_4_4_7_1_5						,  x.dtype )
				__magic_name__						:						Tuple										=0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(lowerCamelCase						,  3 )) ))

				return x * cdf




def 		lowerCAmelCase_ (						lowerCamelCase ):
				__magic_name__						:						Any										=tf.convert_to_tensor(lowerCamelCase )

				return x * tf.tanh(tf.math.softplus(lowerCamelCase ) )




def 		lowerCAmelCase_ (						lowerCamelCase ):
				__magic_name__						:						Optional[Any]										=tf.convert_to_tensor(lowerCamelCase )
				__magic_name__						:						Union[str, Any]										=tf.cast(0.0_4_4_7_1_5						,  x.dtype )
				__magic_name__						:						Tuple										=tf.cast(0.7_9_7_8_8_4_5_6_0_8						,  x.dtype )

				return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) ))




def 		lowerCAmelCase_ (						lowerCamelCase ):
				__magic_name__						:						List[str]										=tf.convert_to_tensor(lowerCamelCase )
				__magic_name__						:						Dict										=tf.cast(1.7_0_2						,  x.dtype )
				return x * tf.math.sigmoid(coeff * x )




def 		lowerCAmelCase_ (						lowerCamelCase ):
				return tf.clip_by_value(_gelu(lowerCamelCase )						,  -10						,  10 )




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase=-1 ):
				__magic_name__					,			__magic_name__						:						List[Any]										=tf.split(lowerCamelCase						,  2						,  axis=lowerCamelCase )
				return a * tf.math.sigmoid(lowerCamelCase )


if version.parse(tf.version.VERSION) >= version.parse("2.4"):




							def 		lowerCAmelCase_ (						lowerCamelCase ):
											return tf.keras.activations.gelu(lowerCamelCase						,  approximate=lowerCamelCase )

							UpperCAmelCase_		:					List[str]          =  tf.keras.activations.gelu



							UpperCAmelCase_		:					Dict          =  approximate_gelu_wrap
else:
							UpperCAmelCase_		:					Dict          =  _gelu
							UpperCAmelCase_		:					str          =  _gelu_new


UpperCAmelCase_		:					Any          =  {
    "gelu": gelu,
    "gelu_10": gelu_aa,
    "gelu_fast": gelu_fast,
    "gelu_new": gelu_new,
    "glu": glu,
    "mish": mish,
    "quick_gelu": quick_gelu,
    "relu": tf.keras.activations.relu,
    "sigmoid": tf.keras.activations.sigmoid,
    "silu": tf.keras.activations.swish,
    "swish": tf.keras.activations.swish,
    "tanh": tf.keras.activations.tanh,
}




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if activation_string in ACTaFN:
								return ACTaFN[activation_string]
				else:
								raise KeyError(F"function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}" )




