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

							"""simple docstring"""






							_snake_case  		=	StableDiffusionXLPipeline
							_snake_case  		=	TEXT_TO_IMAGE_PARAMS
							_snake_case  		=	TEXT_TO_IMAGE_BATCH_PARAMS
							_snake_case  		=	TEXT_TO_IMAGE_IMAGE_PARAMS
							_snake_case  		=	TEXT_TO_IMAGE_IMAGE_PARAMS



							def      A__		(	self      )-> Dict:





													'''simple docstring'''






													torch.manual_seed(0      )
													__UpperCamelCase  	=      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=__SCREAMING_SNAKE_CASE  ,						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  ,						)
													__UpperCamelCase  	=      EulerDiscreteScheduler(
													    beta_start=0.0_0_0_8_5  ,						beta_end=0.0_1_2  ,						steps_offset=1  ,						beta_schedule='''scaled_linear'''  ,						timestep_spacing='''leading'''  ,						)
													torch.manual_seed(0      )
													__UpperCamelCase  	=      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=128  ,						)
													torch.manual_seed(0      )
													__UpperCamelCase  	=      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=1000  ,						hidden_act='''gelu'''  ,						projection_dim=32  ,						)
													__UpperCamelCase  	=      CLIPTextModel(__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  ,						local_files_only=__SCREAMING_SNAKE_CASE      )

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

													__UpperCamelCase  	=      {
													    '''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      A__		(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_=0      )-> Union[str, Any]:





													'''simple docstring'''






													if str(__SCREAMING_SNAKE_CASE      ).startswith('''mps'''      ):
																			__UpperCamelCase  	=      torch.manual_seed(__SCREAMING_SNAKE_CASE      )
													else:
																			__UpperCamelCase  	=      torch.Generator(device=__SCREAMING_SNAKE_CASE      ).manual_seed(__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      {
													    '''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      A__		(	self      )-> Tuple:





													'''simple docstring'''






													__UpperCamelCase  	=      '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase  	=      self.get_dummy_components()
													__UpperCamelCase  	=      StableDiffusionXLPipeline(**__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      sd_pipe.to(__SCREAMING_SNAKE_CASE      )
													sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

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

													assert image.shape == (1, 64, 64, 3)
													__UpperCamelCase  	=      np.array([0.5_8_7_3, 0.6_1_2_8, 0.4_7_9_7, 0.5_1_2_2, 0.5_6_7_4, 0.4_6_3_9, 0.5_2_2_7, 0.5_1_4_9, 0.4_7_4_7]      )

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



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





													'''simple docstring'''






													__UpperCamelCase  	=      self.get_dummy_components()
													__UpperCamelCase  	=      StableDiffusionXLPipeline(**__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      sd_pipe.to(__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      sd_pipe.to(__SCREAMING_SNAKE_CASE      )
													sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

													# forward without prompt embeds
													__UpperCamelCase  	=      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      3 * ['''this is a negative prompt''']
													__UpperCamelCase  	=      negative_prompt
													__UpperCamelCase  	=      3 * [inputs['''prompt''']]

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

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

													(
													    __UpperCamelCase					
													)  	=      sd_pipe.encode_prompt(__SCREAMING_SNAKE_CASE  ,						negative_prompt=__SCREAMING_SNAKE_CASE      )

													__UpperCamelCase  	=      sd_pipe(
													    **__SCREAMING_SNAKE_CASE  ,						prompt_embeds=__SCREAMING_SNAKE_CASE  ,						negative_prompt_embeds=__SCREAMING_SNAKE_CASE  ,						pooled_prompt_embeds=__SCREAMING_SNAKE_CASE  ,						negative_pooled_prompt_embeds=__SCREAMING_SNAKE_CASE  ,						)
													__UpperCamelCase  	=      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      A__		(	self      )-> str:





													'''simple docstring'''






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



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





													'''simple docstring'''






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






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

							"""simple docstring"""






							def      A__		(	self      )-> Optional[Any]:





													'''simple docstring'''






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



							def      A__		(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_="cpu"  ,						SCREAMING_SNAKE_CASE_=torch.floataa  ,						SCREAMING_SNAKE_CASE_=0      )-> List[Any]:





													'''simple docstring'''






													__UpperCamelCase  	=      torch.Generator(device=__SCREAMING_SNAKE_CASE      ).manual_seed(__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      np.random.RandomState(__SCREAMING_SNAKE_CASE      ).standard_normal((1, 4, 64, 64)      )
													__UpperCamelCase  	=      torch.from_numpy(__SCREAMING_SNAKE_CASE      ).to(device=__SCREAMING_SNAKE_CASE  ,						dtype=__SCREAMING_SNAKE_CASE      )
													__UpperCamelCase  	=      {
													    '''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      A__		(	self      )-> Tuple:





													'''simple docstring'''






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

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

													assert image.shape == (1, 512, 512, 3)
													__UpperCamelCase  	=      np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6]      )
													assert np.abs(image_slice - expected_slice      ).max() < 7E-3






'''simple docstring'''







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import DeiTImageProcessor






class 					lowerCAmelCase__  (    unittest.TestCase	):






					def __init__(  self							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE=7							,				__SCREAMING_SNAKE_CASE=3							,				__SCREAMING_SNAKE_CASE=18							,				__SCREAMING_SNAKE_CASE=30							,				__SCREAMING_SNAKE_CASE=4_00							,				__SCREAMING_SNAKE_CASE=True							,				__SCREAMING_SNAKE_CASE=None							,				__SCREAMING_SNAKE_CASE=True							,				__SCREAMING_SNAKE_CASE=None							,				__SCREAMING_SNAKE_CASE=True							,				__SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]							,				__SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]							,				):


											"""simple docstring"""





											lowercase_      :	Union[str, Any]						=			size if size is not None else {'''height''': 20, '''width''': 20}
											lowercase_      :	List[Any]						=			crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

											lowercase_      :	List[str]						=			parent
											lowercase_      :	Optional[Any]						=			batch_size
											lowercase_      :	int						=			num_channels
											lowercase_      :	List[str]						=			image_size
											lowercase_      :	Optional[Any]						=			min_resolution
											lowercase_      :	Tuple						=			max_resolution
											lowercase_      :	Union[str, Any]						=			do_resize
											lowercase_      :	List[str]						=			size
											lowercase_      :	Tuple						=			do_center_crop
											lowercase_      :	Dict						=			crop_size
											lowercase_      :	int						=			do_normalize
											lowercase_      :	Optional[int]						=			image_mean
											lowercase_      :	List[str]						=			image_std






					def       _snake_case       (  self						):


											"""simple docstring"""





											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											}







@require_torch
@require_vision
class 					lowerCAmelCase__  (    lowerCamelCase_       ,		unittest.TestCase	):
					lowerCAmelCase_	  =	DeiTImageProcessor if is_vision_available() else None
					lowerCAmelCase_	  =	True






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	List[str]						=			DeiTImageProcessingTester(self						)






					@property
					def       _snake_case       (  self						):


											"""simple docstring"""





											return self.image_processor_tester.prepare_image_processor_dict()






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	str						=			self.image_processing_class(**self.image_processor_dict						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''do_resize'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''size'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''do_center_crop'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''center_crop'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''do_normalize'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''image_mean'''						)						)
											self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE							,				'''image_std'''						)						)






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	List[str]						=			self.image_processing_class.from_dict(self.image_processor_dict						)
											self.assertEqual(image_processor.size							,				{'''height''': 20, '''width''': 20}						)
											self.assertEqual(image_processor.crop_size							,				{'''height''': 18, '''width''': 18}						)

											lowercase_      :	List[str]						=			self.image_processing_class.from_dict(self.image_processor_dict							,				size=42							,				crop_size=84						)
											self.assertEqual(image_processor.size							,				{'''height''': 42, '''width''': 42}						)
											self.assertEqual(image_processor.crop_size							,				{'''height''': 84, '''width''': 84}						)






					def       _snake_case       (  self						):


											"""simple docstring"""





											pass






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Tuple						=			self.image_processing_class(**self.image_processor_dict						)
											# create random PIL images
											lowercase_      :	Optional[int]						=			prepare_image_inputs(self.image_processor_tester							,				equal_resolution=__SCREAMING_SNAKE_CASE						)
											for image in image_inputs:
																	self.assertIsInstance(__SCREAMING_SNAKE_CASE							,				Image.Image						)

											# Test not batched input
											lowercase_      :	List[Any]						=			image_processing(image_inputs[0]							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)

											# Test batched
											lowercase_      :	List[str]						=			image_processing(__SCREAMING_SNAKE_CASE							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	List[Any]						=			self.image_processing_class(**self.image_processor_dict						)
											# create random numpy tensors
											lowercase_      :	Tuple						=			prepare_image_inputs(self.image_processor_tester							,				equal_resolution=__SCREAMING_SNAKE_CASE							,				numpify=__SCREAMING_SNAKE_CASE						)
											for image in image_inputs:
																	self.assertIsInstance(__SCREAMING_SNAKE_CASE							,				np.ndarray						)

											# Test not batched input
											lowercase_      :	Dict						=			image_processing(image_inputs[0]							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)

											# Test batched
											lowercase_      :	Union[str, Any]						=			image_processing(__SCREAMING_SNAKE_CASE							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	List[str]						=			self.image_processing_class(**self.image_processor_dict						)
											# create random PyTorch tensors
											lowercase_      :	List[Any]						=			prepare_image_inputs(self.image_processor_tester							,				equal_resolution=__SCREAMING_SNAKE_CASE							,				torchify=__SCREAMING_SNAKE_CASE						)
											for image in image_inputs:
																	self.assertIsInstance(__SCREAMING_SNAKE_CASE							,				torch.Tensor						)

											# Test not batched input
											lowercase_      :	List[str]						=			image_processing(image_inputs[0]							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)

											# Test batched
											lowercase_      :	Optional[int]						=			image_processing(__SCREAMING_SNAKE_CASE							,				return_tensors='''pt'''						).pixel_values
											self.assertEqual(
											    encoded_images.shape							,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    )							,				)



