


'''simple docstring'''


import unittest

import numpy as np

from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
    expand_dims,
    flatten_dict,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    reshape,
    squeeze,
    transpose,
)


if is_flax_available():
				import jax.numpy as jnp

if is_tf_available():
				import tensorflow as tf

if is_torch_available():
				import torch





class        lowercase__    (		unittest.TestCase   ):





							'''simple docstring'''


							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= {
											    """task_specific_params""": {
											        """summarization""": {"""length_penalty""": 1.0, """max_length""": 128, """min_length""": 12, """num_beams""": 4},
											        """summarization_cnn""": {"""length_penalty""": 2.0, """max_length""": 142, """min_length""": 56, """num_beams""": 4},
											        """summarization_xsum""": {"""length_penalty""": 1.0, """max_length""": 62, """min_length""": 11, """num_beams""": 6},
											    }
											}
											_SCREAMING_SNAKE_CASE					:			str							= {
											    """task_specific_params.summarization.length_penalty""": 1.0,
											    """task_specific_params.summarization.max_length""": 128,
											    """task_specific_params.summarization.min_length""": 12,
											    """task_specific_params.summarization.num_beams""": 4,
											    """task_specific_params.summarization_cnn.length_penalty""": 2.0,
											    """task_specific_params.summarization_cnn.max_length""": 142,
											    """task_specific_params.summarization_cnn.min_length""": 56,
											    """task_specific_params.summarization_cnn.num_beams""": 4,
											    """task_specific_params.summarization_xsum.length_penalty""": 1.0,
											    """task_specific_params.summarization_xsum.max_length""": 62,
											    """task_specific_params.summarization_xsum.min_length""": 11,
											    """task_specific_params.summarization_xsum.num_beams""": 6,
											}

											self.assertEqual(flatten_dict(lowercase_    )       ,   lowercase_    )






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Dict							= np.random.randn(3       ,   4    )
											self.assertTrue(np.allclose(transpose(lowercase_    )       ,   x.transpose()    )    )

											_SCREAMING_SNAKE_CASE					:			str							= np.random.randn(3       ,   4       ,   5    )
											self.assertTrue(np.allclose(transpose(lowercase_       ,   axes=(1, 2, 0)    )       ,   x.transpose((1, 2, 0)    )    )    )






							@require_torch
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			str							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_    )       ,   transpose(lowercase_    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Dict							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_       ,   axes=(1, 2, 0)    )       ,   transpose(lowercase_       ,   axes=(1, 2, 0)    ).numpy()    )    )






							@require_tf
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			int							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_    )       ,   transpose(lowercase_    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Any							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_       ,   axes=(1, 2, 0)    )       ,   transpose(lowercase_       ,   axes=(1, 2, 0)    ).numpy()    )    )






							@require_flax
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			List[Any]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_    )       ,   np.asarray(transpose(lowercase_    )    )    )    )

											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(transpose(lowercase_       ,   axes=(1, 2, 0)    )       ,   np.asarray(transpose(lowercase_       ,   axes=(1, 2, 0)    )    )    )    )






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= np.random.randn(3       ,   4    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (4, 3)    )       ,   np.reshape(lowercase_       ,   (4, 3)    )    )    )

											_SCREAMING_SNAKE_CASE					:			List[str]							= np.random.randn(3       ,   4       ,   5    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (12, 5)    )       ,   np.reshape(lowercase_       ,   (12, 5)    )    )    )






							@require_torch
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Dict							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (4, 3)    )       ,   reshape(lowercase_       ,   (4, 3)    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (12, 5)    )       ,   reshape(lowercase_       ,   (12, 5)    ).numpy()    )    )






							@require_tf
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (4, 3)    )       ,   reshape(lowercase_       ,   (4, 3)    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Dict							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (12, 5)    )       ,   reshape(lowercase_       ,   (12, 5)    ).numpy()    )    )






							@require_flax
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			List[Any]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (4, 3)    )       ,   np.asarray(reshape(lowercase_       ,   (4, 3)    )    )    )    )

											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(3       ,   4       ,   5    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(reshape(lowercase_       ,   (12, 5)    )       ,   np.asarray(reshape(lowercase_       ,   (12, 5)    )    )    )    )






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= np.random.randn(1       ,   3       ,   4    )
											self.assertTrue(np.allclose(squeeze(lowercase_    )       ,   np.squeeze(lowercase_    )    )    )

											_SCREAMING_SNAKE_CASE					:			int							= np.random.randn(1       ,   4       ,   1       ,   5    )
											self.assertTrue(np.allclose(squeeze(lowercase_       ,   axis=2    )       ,   np.squeeze(lowercase_       ,   axis=2    )    )    )






							@require_torch
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(1       ,   3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Any							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_    )       ,   squeeze(lowercase_    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			Any							= np.random.randn(1       ,   4       ,   1       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Dict							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_       ,   axis=2    )       ,   squeeze(lowercase_       ,   axis=2    ).numpy()    )    )






							@require_tf
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Any							= np.random.randn(1       ,   3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			List[Any]							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_    )       ,   squeeze(lowercase_    ).numpy()    )    )

											_SCREAMING_SNAKE_CASE					:			Dict							= np.random.randn(1       ,   4       ,   1       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Dict							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_       ,   axis=2    )       ,   squeeze(lowercase_       ,   axis=2    ).numpy()    )    )






							@require_flax
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Any							= np.random.randn(1       ,   3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Dict							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_    )       ,   np.asarray(squeeze(lowercase_    )    )    )    )

											_SCREAMING_SNAKE_CASE					:			List[str]							= np.random.randn(1       ,   4       ,   1       ,   5    )
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(squeeze(lowercase_       ,   axis=2    )       ,   np.asarray(squeeze(lowercase_       ,   axis=2    )    )    )    )






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.random.randn(3       ,   4    )
											self.assertTrue(np.allclose(expand_dims(lowercase_       ,   axis=1    )       ,   np.expand_dims(lowercase_       ,   axis=1    )    )    )






							@require_torch
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Dict							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Any							= torch.tensor(lowercase_    )
											self.assertTrue(np.allclose(expand_dims(lowercase_       ,   axis=1    )       ,   expand_dims(lowercase_       ,   axis=1    ).numpy()    )    )






							@require_tf
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Dict							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			int							= tf.constant(lowercase_    )
											self.assertTrue(np.allclose(expand_dims(lowercase_       ,   axis=1    )       ,   expand_dims(lowercase_       ,   axis=1    ).numpy()    )    )






							@require_flax
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= np.random.randn(3       ,   4    )
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= jnp.array(lowercase_    )
											self.assertTrue(np.allclose(expand_dims(lowercase_       ,   axis=1    )       ,   np.asarray(expand_dims(lowercase_       ,   axis=1    )    )    )    )








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       lowercase_					(lowercase__      ,					unittest.TestCase   ):
				snake_case	    =KandinskyVaaPriorPipeline
				snake_case	    =['prompt']
				snake_case	    =['prompt', 'negative_prompt']
				snake_case	    =[
				    'num_images_per_prompt',
				    'generator',
				    'num_inference_steps',
				    'latents',
				    'negative_prompt',
				    'guidance_scale',
				    'output_type',
				    'return_dict',
				]
				snake_case	    =False





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											return 32





				@property
				def 						__UpperCamelCase    (				self)  -> Tuple:
											return 32





				@property
				def 						__UpperCamelCase    (				self)  -> int:
											return self.time_input_dim





				@property
				def 						__UpperCamelCase    (				self)  -> str:
											return self.time_input_dim * 4





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											return 100





				@property
				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
											return tokenizer





				@property
				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											torch.manual_seed(0)
											a__      =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=1000       ,  )
											return CLIPTextModelWithProjection(lowercase_)





				@property
				def 						__UpperCamelCase    (				self)  -> Tuple:
											torch.manual_seed(0)

											a__      ={
											    'num_attention_heads': 2,
											    'attention_head_dim': 12,
											    'embedding_dim': self.text_embedder_hidden_size,
											    'num_layers': 1,
											}

											a__      =PriorTransformer(**lowercase_)
											# 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
											a__      =nn.Parameter(torch.ones(model.clip_std.shape))
											return model





				@property
				def 						__UpperCamelCase    (				self)  -> Any:
											torch.manual_seed(0)
											a__      =CLIPVisionConfig(
											    hidden_size=self.text_embedder_hidden_size       ,  image_size=224       ,  projection_dim=self.text_embedder_hidden_size       ,  intermediate_size=37       ,  num_attention_heads=4       ,  num_channels=3       ,  num_hidden_layers=5       ,  patch_size=14       ,  )

											a__      =CLIPVisionModelWithProjection(lowercase_)
											return model





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =CLIPImageProcessor(
											    crop_size=224       ,  do_center_crop=lowercase_       ,  do_normalize=lowercase_       ,  do_resize=lowercase_       ,  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=224       ,  )

											return image_processor





				def 						__UpperCamelCase    (				self)  -> Any:
											a__      =self.dummy_prior
											a__      =self.dummy_image_encoder
											a__      =self.dummy_text_encoder
											a__      =self.dummy_tokenizer
											a__      =self.dummy_image_processor

											a__      =UnCLIPScheduler(
											    variance_type='fixed_small_log'       ,  prediction_type='sample'       ,  num_train_timesteps=1000       ,  clip_sample=lowercase_       ,  clip_sample_range=10.0       ,  )

											a__      ={
											    'prior': prior,
											    'image_encoder': image_encoder,
											    'text_encoder': text_encoder,
											    'tokenizer': tokenizer,
											    'scheduler': scheduler,
											    'image_processor': image_processor,
											}

											return components





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_=0)  -> Tuple:
											if str(lowercase_).startswith('mps'):
																		a__      =torch.manual_seed(lowercase_)
											else:
																		a__      =torch.Generator(device=lowercase_).manual_seed(lowercase_)
											a__      ={
											    'prompt': 'horse',
											    'generator': generator,
											    'guidance_scale': 4.0,
											    'num_inference_steps': 2,
											    'output_type': 'np',
											}
											return inputs





				def 						__UpperCamelCase    (				self)  -> int:
											a__      ='cpu'

											a__      =self.get_dummy_components()

											a__      =self.pipeline_class(**lowercase_)
											a__      =pipe.to(lowercase_)

											pipe.set_progress_bar_config(disable=lowercase_)

											a__      =pipe(**self.get_dummy_inputs(lowercase_))
											a__      =output.image_embeds

											a__      =pipe(
											    **self.get_dummy_inputs(lowercase_)       ,  return_dict=lowercase_       ,  )[0]

											a__      =image[0, -10:]
											a__      =image_from_tuple[0, -10:]

											assert image.shape == (1, 32)

											a__      =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 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =torch_device == 'cpu'
											a__      =True
											a__      =False

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





				@skip_mps
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =torch_device == 'cpu'
											a__      =False

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

