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				(						lowercase_						,unittest.TestCase			):


   """simple docstring"""






   __a  :			Any      			=						KandinskyPriorPipeline
   __a  :			str      			=						["""prompt"""]
   __a  :			Optional[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  :			Tuple      			=						False





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Optional[int]:

       '''simple docstring'''


       return 32





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

       '''simple docstring'''


       return 32





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> int:

       '''simple docstring'''


       return self.time_input_dim





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[Any]:

       '''simple docstring'''


       return self.time_input_dim * 4





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> int:

       '''simple docstring'''


       return 1_00





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> str:

       '''simple docstring'''


       __lowercase			      =							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)
       return tokenizer





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Union[str, Any]:

       '''simple docstring'''


       torch.manual_seed(0						)
       __lowercase			      =							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(lowerCAmelCase__						)





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Optional[int]:

       '''simple docstring'''


       torch.manual_seed(0						)

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

       __lowercase			      =							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
       __lowercase			      =							nn.Parameter(torch.ones(model.clip_std.shape						)						)
       return model





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[str]:

       '''simple docstring'''


       torch.manual_seed(0						)
       __lowercase			      =							CLIPVisionConfig(
           hidden_size=self.text_embedder_hidden_size				,       image_size=2_24				,       projection_dim=self.text_embedder_hidden_size				,       intermediate_size=37				,       num_attention_heads=4				,       num_channels=3				,       num_hidden_layers=5				,       patch_size=14				,       )

       __lowercase			      =							CLIPVisionModelWithProjection(lowerCAmelCase__						)
       return model





   @property
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Optional[int]:

       '''simple docstring'''


       __lowercase			      =							CLIPImageProcessor(
           crop_size=2_24				,       do_center_crop=lowerCAmelCase__				,       do_normalize=lowerCAmelCase__				,       do_resize=lowerCAmelCase__				,       image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]				,       image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]				,       resample=3				,       size=2_24				,       )

       return image_processor





   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

       '''simple docstring'''


       __lowercase			      =							self.dummy_prior
       __lowercase			      =							self.dummy_image_encoder
       __lowercase			      =							self.dummy_text_encoder
       __lowercase			      =							self.dummy_tokenizer
       __lowercase			      =							self.dummy_image_processor

       __lowercase			      =							UnCLIPScheduler(
           variance_type='''fixed_small_log'''				,       prediction_type='''sample'''				,       num_train_timesteps=10_00				,       clip_sample=lowerCAmelCase__				,       clip_sample_range=10.0				,       )

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

       return components





   def 	_SCREAMING_SNAKE_CASE      (       self				,       lowerCAmelCase__				,       lowerCAmelCase__=0						)					-> List[Any]:

       '''simple docstring'''


       if str(lowerCAmelCase__						).startswith('''mps'''						):
           __lowercase			      =							torch.manual_seed(lowerCAmelCase__						)
       else:
           __lowercase			      =							torch.Generator(device=lowerCAmelCase__						).manual_seed(lowerCAmelCase__						)
       __lowercase			      =							{
           '''prompt''': '''horse''',
           '''generator''': generator,
           '''guidance_scale''': 4.0,
           '''num_inference_steps''': 2,
           '''output_type''': '''np''',
       }
       return inputs





   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

       '''simple docstring'''


       __lowercase			      =							'''cpu'''

       __lowercase			      =							self.get_dummy_components()

       __lowercase			      =							self.pipeline_class(**lowerCAmelCase__						)
       __lowercase			      =							pipe.to(lowerCAmelCase__						)

       pipe.set_progress_bar_config(disable=lowerCAmelCase__						)

       __lowercase			      =							pipe(**self.get_dummy_inputs(lowerCAmelCase__						)						)
       __lowercase			      =							output.image_embeds

       __lowercase			      =							pipe(
           **self.get_dummy_inputs(lowerCAmelCase__						)				,       return_dict=lowerCAmelCase__				,       )[0]

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

       assert image.shape == (1, 32)

       __lowercase			      =							np.array(
           [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]						)

       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 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[Any]:

       '''simple docstring'''


       __lowercase			      =							torch_device == '''cpu'''
       __lowercase			      =							True
       __lowercase			      =							False

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





   @skip_mps
   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Optional[int]:

       '''simple docstring'''


       __lowercase			      =							torch_device == '''cpu'''
       __lowercase			      =							False

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




class        _UpperCamelCase				:


			"""simple docstring"""






			def __init__(       self				,       lowerCAmelCase__						)					-> List[str]:

							'''simple docstring'''


							if isinstance(lowerCAmelCase__				,       lowerCAmelCase__						):  # Initializes a matrix identical to the one provided.
											__lowercase			      =							arg
											__lowercase			      =							len(lowerCAmelCase__						)
							else:  # Initializes a square matrix of the given size and set values to zero.
											__lowercase			      =							arg
											__lowercase			      =							[[0 for _ in range(self.n						)] for _ in range(self.n						)]





			def __mul__(       self				,       lowerCAmelCase__						)					-> str:

							'''simple docstring'''


							__lowercase			      =							Matrix(self.n						)
							for i in range(self.n						):
											for j in range(self.n						):
															for k in range(self.n						):
																			matrix.t[i][j] += self.t[i][k] * b.t[k][j]
							return matrix





def     UpperCAmelCase						(   lowercase							,      lowercase							):







				"""simple docstring"""



				__lowercase			      =							Matrix([[1, 0], [0, 1]]							)
				while b > 0:
								if b & 1:
												matrix *= a
								a *= a
								b >>= 1
				return matrix





def     UpperCAmelCase						(   lowercase							,      lowercase							,      lowercase							):







				"""simple docstring"""



				if n == 1:
								return fa
				elif n == 2:
								return fa
				__lowercase			      =							Matrix([[1, 1], [1, 0]]							)
				__lowercase			      =							modular_exponentiation(lowercase							,      n - 2							)
				return fa * matrix.t[0][0] + fa * matrix.t[0][1]





def     UpperCAmelCase						(   lowercase							,      lowercase							,      lowercase							):







				"""simple docstring"""



				if n == 1:
								return fa
				elif n == 2:
								return fa

				__lowercase			      =							fa
				__lowercase			      =							fa
				n -= 2

				while n > 0:
								__lowercase      ,					__lowercase			      =							fn_a + fn_a, fn_a
								n -= 1

				return fn_a





def     UpperCAmelCase						(   ):







				"""simple docstring"""



				__lowercase			      =							'''
from random import randint
from __main__ import fibonacci_with_matrix_exponentiation
'''
				__lowercase			      =							'''fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)'''
				__lowercase			      =							timeit.timeit(setup=lowercase							,      stmt=lowercase							,      number=100							)
				print('''With matrix exponentiation the average execution time is '''							,      exec_time / 100							)
				return exec_time





def     UpperCAmelCase						(   ):







				"""simple docstring"""



				__lowercase			      =							'''
from random import randint
from __main__ import simple_fibonacci
'''
				__lowercase			      =							'''simple_fibonacci(randint(1,70000), 1, 1)'''
				__lowercase			      =							timeit.timeit(setup=lowercase							,      stmt=lowercase							,      number=100							)
				print(
				    '''Without matrix exponentiation the average execution time is '''							,      exec_time / 100							)
				return exec_time





def     UpperCAmelCase						(   ):







				"""simple docstring"""



				matrix_exponentiation_time()
				simple_fibonacci_time()


if __name__ == "__main__":
		main()