



'''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 KandinskyPriorPipeline, 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  (							lowerCamelCase__   , unittest.TestCase   ):


			'''simple docstring'''

			_A				:		Optional[Any]         =		KandinskyPriorPipeline
			_A				:		Optional[int]         =		['''prompt''']
			_A				:		int         =		['''prompt''', '''negative_prompt''']
			_A				:		Optional[int]         =		[
			    '''num_images_per_prompt''',
			    '''generator''',
			    '''num_inference_steps''',
			    '''latents''',
			    '''negative_prompt''',
			    '''guidance_scale''',
			    '''output_type''',
			    '''return_dict''',
			]
			_A				:		List[str]         =		False

			@property
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					return 3_2

			@property
			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					return 3_2

			@property
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					return self.time_input_dim

			@property
			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					return self.time_input_dim * 4

			@property
			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






					return 1_0_0

			@property
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[str]   	=		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""						)
					return tokenizer

			@property
			def UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






					torch.manual_seed(0						)
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		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-05							,					num_attention_heads=4							,					num_hidden_layers=5							,					pad_token_id=1							,					vocab_size=1_0_0_0							,					)
					return CLIPTextModelWithProjection(lowerCAmelCase__						)

			@property
			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					torch.manual_seed(0						)

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

					__SCREAMING_SNAKE_CASE	:		Dict   	=		PriorTransformer(**lowerCAmelCase__						)
					# 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
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		nn.Parameter(torch.ones(model.clip_std.shape						)						)
					return model

			@property
			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					torch.manual_seed(0						)
					__SCREAMING_SNAKE_CASE	:		str   	=		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							,					)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		CLIPVisionModelWithProjection(lowerCAmelCase__						)
					return model

			@property
			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		CLIPImageProcessor(
					    crop_size=2_2_4							,					do_center_crop=lowerCAmelCase__							,					do_normalize=lowerCAmelCase__							,					do_resize=lowerCAmelCase__							,					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 UpperCamelCase__ (							self					:			Dict						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		int   	=		self.dummy_prior
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.dummy_image_encoder
					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.dummy_text_encoder
					__SCREAMING_SNAKE_CASE	:		Any   	=		self.dummy_tokenizer
					__SCREAMING_SNAKE_CASE	:		str   	=		self.dummy_image_processor

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		UnCLIPScheduler(
					    variance_type="""fixed_small_log"""							,					prediction_type="""sample"""							,					num_train_timesteps=1_0_0_0							,					clip_sample=lowerCAmelCase__							,					clip_sample_range=10.0							,					)

					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		{
					    """prior""": prior,
					    """image_encoder""": image_encoder,
					    """text_encoder""": text_encoder,
					    """tokenizer""": tokenizer,
					    """scheduler""": scheduler,
					    """image_processor""": image_processor,
					}

					return components

			def UpperCamelCase__ (							self					:			Any							,					lowerCAmelCase__					:			Union[str, Any]							,					lowerCAmelCase__					:			Dict=0						):





					"""simple docstring"""






					if str(lowerCAmelCase__						).startswith("""mps"""						):
							__SCREAMING_SNAKE_CASE	:		int   	=		torch.manual_seed(lowerCAmelCase__						)
					else:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.Generator(device=lowerCAmelCase__						).manual_seed(lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		{
					    """prompt""": """horse""",
					    """generator""": generator,
					    """guidance_scale""": 4.0,
					    """num_inference_steps""": 2,
					    """output_type""": """np""",
					}
					return inputs

			def UpperCamelCase__ (							self					:			Optional[int]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		"""cpu"""

					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.get_dummy_components()

					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		self.pipeline_class(**lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Dict   	=		pipe.to(lowerCAmelCase__						)

					pipe.set_progress_bar_config(disable=lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		pipe(**self.get_dummy_inputs(lowerCAmelCase__						)						)
					__SCREAMING_SNAKE_CASE	:		str   	=		output.image_embeds

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		pipe(
					    **self.get_dummy_inputs(lowerCAmelCase__						)							,					return_dict=lowerCAmelCase__							,					)[0]

					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		image[0, -1_0:]
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		image_from_tuple[0, -1_0:]

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

					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		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					:			Dict						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch_device == """cpu"""
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		True
					__SCREAMING_SNAKE_CASE	:		Dict   	=		False

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



			@skip_mps
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		torch_device == """cpu"""
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		False

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




'''simple docstring'''




UpperCamelCase__	:     List[Any]    =			10_00


def     lowerCAmelCase_       (     _lowerCamelCase:       float ):
		return x * x


def     lowerCAmelCase_       (     _lowerCamelCase:       Any	,				_lowerCamelCase:       float	,				_lowerCamelCase:       float	,				_lowerCamelCase:       int = 4 ):
		assert callable(
		    _lowerCamelCase ), F"the function(object) passed should be callable your input : {function}"
		assert isinstance(_lowerCamelCase	,				(float, int) ), F"a should be float or integer your input : {a}"
		assert isinstance(function(_lowerCamelCase )	,				(float, int) ), (
		    "the function should return integer or float return type of your function, "
		    F"{type(_lowerCamelCase )}"
		)
		assert isinstance(_lowerCamelCase	,				(float, int) ), F"b should be float or integer your input : {b}"
		assert (
		    isinstance(_lowerCamelCase	,				_lowerCamelCase ) and precision > 0
		), F"precision should be positive integer your input : {precision}"

		# just applying the formula of simpson for approximate integration written in
		# mentioned article in first comment of this file and above this function

		__SCREAMING_SNAKE_CASE	:		List[Any]   	=		(b - a) / N_STEPS
		__SCREAMING_SNAKE_CASE	:		List[Any]   	=		function(_lowerCamelCase ) + function(_lowerCamelCase )

		for i in range(1	,				_lowerCamelCase ):
				__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		a + h * i
				result += function(_lowerCamelCase ) * (4 if i % 2 else 2)

		result *= h / 3
		return round(_lowerCamelCase	,				_lowerCamelCase )


if __name__ == "__main__":
						import doctest

						doctest.testmod()