


'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A	:	Optional[int]     =     {
    'configuration_clap': [
        'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST',
        'ClapAudioConfig',
        'ClapConfig',
        'ClapTextConfig',
    ],
    'processing_clap': ['ClapProcessor'],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__A	:	List[Any]     =     [
							    'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST',
							    'ClapModel',
							    'ClapPreTrainedModel',
							    'ClapTextModel',
							    'ClapTextModelWithProjection',
							    'ClapAudioModel',
							    'ClapAudioModelWithProjection',
							]
							__A	:	str     =     ['ClapFeatureExtractor']

if TYPE_CHECKING:
							from .configuration_clap import (
							    CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
							    ClapAudioConfig,
							    ClapConfig,
							    ClapTextConfig,
							)
							from .processing_clap import ClapProcessor

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .feature_extraction_clap import ClapFeatureExtractor
														from .modeling_clap import (
														    CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
														    ClapAudioModel,
														    ClapAudioModelWithProjection,
														    ClapModel,
														    ClapPreTrainedModel,
														    ClapTextModel,
														    ClapTextModelWithProjection,
														)


else:
							import sys

							__A	:	Dict     =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



'''simple docstring'''






import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 						__UpperCamelCase	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		List[str]   		=  KandinskyVaaPriorPipeline
							lowercase			:		Optional[Any]   		=  ['prompt']
							lowercase			:		Dict   		=  ['prompt', 'negative_prompt']
							lowercase			:		Dict   		=  [
							    'num_images_per_prompt',
							    'generator',
							    'num_inference_steps',
							    'latents',
							    'negative_prompt',
							    'guidance_scale',
							    'output_type',
							    'return_dict',
							]
							lowercase			:		int   		=  False





							@property
							def 		a__   (  self		:int			):
									return 3_2





							@property
							def 		a__   (  self		:Any			):
									return 3_2





							@property
							def 		a__   (  self		:Union[str, Any]			):
									return self.time_input_dim





							@property
							def 		a__   (  self		:int			):
									return self.time_input_dim * 4





							@property
							def 		a__   (  self		:Dict			):
									return 1_0_0





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							List[Any]			       =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
									return tokenizer





							@property
							def 		a__   (  self		:int			):
									torch.manual_seed(0			)
									snake_case_		:							Optional[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=3_7  ,layer_norm_eps=1E-0_5  ,num_attention_heads=4  ,num_hidden_layers=5  ,pad_token_id=1  ,vocab_size=1_0_0_0  ,)
									return CLIPTextModelWithProjection(_UpperCamelCase			)





							@property
							def 		a__   (  self		:Dict			):
									torch.manual_seed(0			)

									snake_case_		:							Tuple			       =						{
									    """num_attention_heads""": 2,
									    """attention_head_dim""": 1_2,
									    """embedding_dim""": self.text_embedder_hidden_size,
									    """num_layers""": 1,
									}

									snake_case_		:							int			       =						PriorTransformer(**_UpperCamelCase			)
									# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
									snake_case_		:							Any			       =						nn.Parameter(torch.ones(model.clip_std.shape			)			)
									return model





							@property
							def 		a__   (  self		:Optional[int]			):
									torch.manual_seed(0			)
									snake_case_		:							Any			       =						CLIPVisionConfig(
									    hidden_size=self.text_embedder_hidden_size  ,image_size=2_2_4  ,projection_dim=self.text_embedder_hidden_size  ,intermediate_size=3_7  ,num_attention_heads=4  ,num_channels=3  ,num_hidden_layers=5  ,patch_size=1_4  ,)

									snake_case_		:							Optional[Any]			       =						CLIPVisionModelWithProjection(_UpperCamelCase			)
									return model





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						CLIPImageProcessor(
									    crop_size=2_2_4  ,do_center_crop=_UpperCamelCase  ,do_normalize=_UpperCamelCase  ,do_resize=_UpperCamelCase  ,image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]  ,image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]  ,resample=3  ,size=2_2_4  ,)

									return image_processor





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Tuple			       =						self.dummy_prior
									snake_case_		:							Any			       =						self.dummy_image_encoder
									snake_case_		:							Optional[int]			       =						self.dummy_text_encoder
									snake_case_		:							Any			       =						self.dummy_tokenizer
									snake_case_		:							Union[str, Any]			       =						self.dummy_image_processor

									snake_case_		:							Tuple			       =						UnCLIPScheduler(
									    variance_type="""fixed_small_log"""  ,prediction_type="""sample"""  ,num_train_timesteps=1_0_0_0  ,clip_sample=_UpperCamelCase  ,clip_sample_range=10.0  ,)

									snake_case_		:							Tuple			       =						{
									    """prior""": prior,
									    """image_encoder""": image_encoder,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """scheduler""": scheduler,
									    """image_processor""": image_processor,
									}

									return components





							def 		a__   (  self		:Dict  ,_UpperCamelCase		:str  ,_UpperCamelCase		:Union[str, Any]=0			):
									if str(_UpperCamelCase			).startswith("""mps"""			):
											snake_case_		:							Optional[int]			       =						torch.manual_seed(_UpperCamelCase			)
									else:
											snake_case_		:							int			       =						torch.Generator(device=_UpperCamelCase			).manual_seed(_UpperCamelCase			)
									snake_case_		:							Dict			       =						{
									    """prompt""": """horse""",
									    """generator""": generator,
									    """guidance_scale""": 4.0,
									    """num_inference_steps""": 2,
									    """output_type""": """np""",
									}
									return inputs





							def 		a__   (  self		:int			):
									snake_case_		:							Union[str, Any]			       =						"""cpu"""

									snake_case_		:							int			       =						self.get_dummy_components()

									snake_case_		:							int			       =						self.pipeline_class(**_UpperCamelCase			)
									snake_case_		:							Union[str, Any]			       =						pipe.to(_UpperCamelCase			)

									pipe.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Any			       =						pipe(**self.get_dummy_inputs(_UpperCamelCase			)			)
									snake_case_		:							List[Any]			       =						output.image_embeds

									snake_case_		:							List[Any]			       =						pipe(
									    **self.get_dummy_inputs(_UpperCamelCase			)  ,return_dict=_UpperCamelCase  ,)[0]

									snake_case_		:							Dict			       =						image[0, -1_0:]
									snake_case_		:							Optional[Any]			       =						image_from_tuple[0, -1_0:]

									assert image.shape == (1, 3_2)

									snake_case_		:							Optional[int]			       =						np.array(
									    [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]			)

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





							@skip_mps
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						torch_device == """cpu"""
									snake_case_		:							Any			       =						True
									snake_case_		:							Dict			       =						False

									self._test_inference_batch_single_identical(
									    test_max_difference=_UpperCamelCase  ,relax_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)





							@skip_mps
							def 		a__   (  self		:str			):
									snake_case_		:							str			       =						torch_device == """cpu"""
									snake_case_		:							List[str]			       =						False

									self._test_attention_slicing_forward_pass(
									    test_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)