import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class        _UpperCamelCase				(						_UpperCAmelCase						,_UpperCAmelCase						,unittest.TestCase			):


   """simple docstring"""






   __a  :			List[Any]      			=						StableDiffusionXLPipeline
   __a  :			List[Any]      			=						TEXT_TO_IMAGE_PARAMS
   __a  :			Optional[int]      			=						TEXT_TO_IMAGE_BATCH_PARAMS
   __a  :			Optional[Any]      			=						TEXT_TO_IMAGE_IMAGE_PARAMS
   __a  :			Optional[Any]      			=						TEXT_TO_IMAGE_IMAGE_PARAMS





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

       '''simple docstring'''


       torch.manual_seed(0						)
       __lowercase			      =							UNetaDConditionModel(
           block_out_channels=(32, 64)				,       layers_per_block=2				,       sample_size=32				,       in_channels=4				,       out_channels=4				,       down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')				,       up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')				,       attention_head_dim=(2, 4)				,       use_linear_projection=__A				,       addition_embed_type='''text_time'''				,       addition_time_embed_dim=8				,       transformer_layers_per_block=(1, 2)				,       projection_class_embeddings_input_dim=80				,       cross_attention_dim=64				,       )
       __lowercase			      =							EulerDiscreteScheduler(
           beta_start=0.0_0085				,       beta_end=0.012				,       steps_offset=1				,       beta_schedule='''scaled_linear'''				,       timestep_spacing='''leading'''				,       )
       torch.manual_seed(0						)
       __lowercase			      =							AutoencoderKL(
           block_out_channels=[32, 64]				,       in_channels=3				,       out_channels=3				,       down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']				,       up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']				,       latent_channels=4				,       sample_size=1_28				,       )
       torch.manual_seed(0						)
       __lowercase			      =							CLIPTextConfig(
           bos_token_id=0				,       eos_token_id=2				,       hidden_size=32				,       intermediate_size=37				,       layer_norm_eps=1E-05				,       num_attention_heads=4				,       num_hidden_layers=5				,       pad_token_id=1				,       vocab_size=10_00				,       hidden_act='''gelu'''				,       projection_dim=32				,       )
       __lowercase			      =							CLIPTextModel(__A						)
       __lowercase			      =							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				,       local_files_only=__A						)

       __lowercase			      =							CLIPTextModelWithProjection(__A						)
       __lowercase			      =							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				,       local_files_only=__A						)

       __lowercase			      =							{
           "unet": unet,
           "scheduler": scheduler,
           "vae": vae,
           "text_encoder": text_encoder,
           "tokenizer": tokenizer,
           "text_encoder_2": text_encoder_a,
           "tokenizer_2": tokenizer_a,
           # "safety_checker": None,
           # "feature_extractor": None,
       }
       return components





   def 	_SCREAMING_SNAKE_CASE      (       self				,       lowerCAmelCase__				,       lowerCAmelCase__=0						)					-> Tuple:

       '''simple docstring'''


       if str(__A						).startswith('''mps'''						):
           __lowercase			      =							torch.manual_seed(__A						)
       else:
           __lowercase			      =							torch.Generator(device=__A						).manual_seed(__A						)
       __lowercase			      =							{
           "prompt": "A painting of a squirrel eating a burger",
           "generator": generator,
           "num_inference_steps": 2,
           "guidance_scale": 5.0,
           "output_type": "numpy",
       }
       return inputs





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

       '''simple docstring'''


       __lowercase			      =							"cpu"  # ensure determinism for the device-dependent torch.Generator
       __lowercase			      =							self.get_dummy_components()
       __lowercase			      =							StableDiffusionXLPipeline(**__A						)
       __lowercase			      =							sd_pipe.to(__A						)
       sd_pipe.set_progress_bar_config(disable=__A						)

       __lowercase			      =							self.get_dummy_inputs(__A						)
       __lowercase			      =							sd_pipe(**__A						).images
       __lowercase			      =							image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       __lowercase			      =							np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]						)

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





   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> str:

       '''simple docstring'''


       __lowercase			      =							self.get_dummy_components()
       __lowercase			      =							StableDiffusionXLPipeline(**__A						)
       __lowercase			      =							sd_pipe.to(__A						)
       __lowercase			      =							sd_pipe.to(__A						)
       sd_pipe.set_progress_bar_config(disable=__A						)

       # forward without prompt embeds
       __lowercase			      =							self.get_dummy_inputs(__A						)
       __lowercase			      =							3 * ["this is a negative prompt"]
       __lowercase			      =							negative_prompt
       __lowercase			      =							3 * [inputs["prompt"]]

       __lowercase			      =							sd_pipe(**__A						)
       __lowercase			      =							output.images[0, -3:, -3:, -1]

       # forward with prompt embeds
       __lowercase			      =							self.get_dummy_inputs(__A						)
       __lowercase			      =							3 * ["this is a negative prompt"]
       __lowercase			      =							3 * [inputs.pop('''prompt'''						)]

       (
           __lowercase     
       )			      =							sd_pipe.encode_prompt(__A				,       negative_prompt=__A						)

       __lowercase			      =							sd_pipe(
           **__A				,       prompt_embeds=__A				,       negative_prompt_embeds=__A				,       pooled_prompt_embeds=__A				,       negative_pooled_prompt_embeds=__A				,       )
       __lowercase			      =							output.images[0, -3:, -3:, -1]

       # make sure that it's equal
       assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()						).max() < 1E-4





   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> str:

       '''simple docstring'''


       super().test_attention_slicing_forward_pass(expected_max_diff=3E-3						)





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

       '''simple docstring'''


       super().test_inference_batch_single_identical(expected_max_diff=3E-3						)




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


   """simple docstring"""






   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

       '''simple docstring'''


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





   def 	_SCREAMING_SNAKE_CASE      (       self				,       lowerCAmelCase__				,       lowerCAmelCase__="cpu"				,       lowerCAmelCase__=torch.floataa				,       lowerCAmelCase__=0						)					-> Any:

       '''simple docstring'''


       __lowercase			      =							torch.Generator(device=__A						).manual_seed(__A						)
       __lowercase			      =							np.random.RandomState(__A						).standard_normal((1, 4, 64, 64)						)
       __lowercase			      =							torch.from_numpy(__A						).to(device=__A				,       dtype=__A						)
       __lowercase			      =							{
           "prompt": "a photograph of an astronaut riding a horse",
           "latents": latents,
           "generator": generator,
           "num_inference_steps": 3,
           "guidance_scale": 7.5,
           "output_type": "numpy",
       }
       return inputs





   def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Dict:

       '''simple docstring'''


       __lowercase			      =							DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''						)
       pipe.to(__A						)
       pipe.set_progress_bar_config(disable=__A						)

       __lowercase			      =							self.get_inputs(__A						)
       __lowercase			      =							pipe(**__A						).images
       __lowercase			      =							image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 5_12, 5_12, 3)
       __lowercase			      =							np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]						)
       assert np.abs(image_slice - expected_slice						).max() < 7E-3
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()