



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







	"""simple docstring"""






	lowerCamelCase__      			=	StableDiffusionXLPipeline
	lowerCamelCase__      			=	TEXT_TO_IMAGE_PARAMS
	lowerCamelCase__      			=	TEXT_TO_IMAGE_BATCH_PARAMS
	lowerCamelCase__      			=	TEXT_TO_IMAGE_IMAGE_PARAMS
	lowerCamelCase__      			=	TEXT_TO_IMAGE_IMAGE_PARAMS







	def 					A     (						self      :					str		)      ->		Optional[Any]:
								torch.manual_seed(0		)
								UpperCAmelCase			:	str										=		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		,      )
								UpperCAmelCase			:	Dict										=		EulerDiscreteScheduler(
								    beta_start=0.0_00_85		,      beta_end=0.0_12		,      steps_offset=1		,      beta_schedule='''scaled_linear'''		,      timestep_spacing='''leading'''		,      )
								torch.manual_seed(0		)
								UpperCAmelCase			:	int										=		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			:	Dict										=		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			:	List[Any]										=		CLIPTextModel(__A		)
								UpperCAmelCase			:	int										=		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		,      local_files_only=__A		)

								UpperCAmelCase			:	Optional[Any]										=		CLIPTextModelWithProjection(__A		)
								UpperCAmelCase			:	Optional[Any]										=		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		,      local_files_only=__A		)

								UpperCAmelCase			:	Optional[Any]										=		{
								    "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      :					Union[str, Any]		,      __snake_case      :					Optional[Any]		,      __snake_case      :					Any=0		)      ->		Dict:





								if str(__A		).startswith('''mps'''		):
															UpperCAmelCase			:	Any										=		torch.manual_seed(__A		)
								else:
															UpperCAmelCase			:	Union[str, Any]										=		torch.Generator(device=__A		).manual_seed(__A		)
								UpperCAmelCase			:	Union[str, Any]										=		{
								    "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      :					Optional[int]		)      ->		Any:
								UpperCAmelCase			:	Optional[Any]										=		"cpu"  # ensure determinism for the device-dependent torch.Generator
								UpperCAmelCase			:	Optional[int]										=		self.get_dummy_components()
								UpperCAmelCase			:	Dict										=		StableDiffusionXLPipeline(**__A		)
								UpperCAmelCase			:	str										=		sd_pipe.to(__A		)
								sd_pipe.set_progress_bar_config(disable=__A		)

								UpperCAmelCase			:	int										=		self.get_dummy_inputs(__A		)
								UpperCAmelCase			:	Tuple										=		sd_pipe(**__A		).images
								UpperCAmelCase			:	Any										=		image[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								UpperCAmelCase			:	Tuple										=		np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]		)

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







	def 					A     (						self      :					List[Any]		)      ->		Optional[Any]:
								UpperCAmelCase			:	Tuple										=		self.get_dummy_components()
								UpperCAmelCase			:	Optional[Any]										=		StableDiffusionXLPipeline(**__A		)
								UpperCAmelCase			:	Dict										=		sd_pipe.to(__A		)
								UpperCAmelCase			:	Optional[Any]										=		sd_pipe.to(__A		)
								sd_pipe.set_progress_bar_config(disable=__A		)

								# forward without prompt embeds
								UpperCAmelCase			:	List[Any]										=		self.get_dummy_inputs(__A		)
								UpperCAmelCase			:	int										=		3 * ["this is a negative prompt"]
								UpperCAmelCase			:	Tuple										=		negative_prompt
								UpperCAmelCase			:	Any										=		3 * [inputs["prompt"]]

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

								# forward with prompt embeds
								UpperCAmelCase			:	List[str]										=		self.get_dummy_inputs(__A		)
								UpperCAmelCase			:	Optional[Any]										=		3 * ["this is a negative prompt"]
								UpperCAmelCase			:	str										=		3 * [inputs.pop('''prompt'''		)]

								(
								    UpperCAmelCase     
								)			:	Optional[Any]										=		sd_pipe.encode_prompt(__A		,      negative_prompt=__A		)

								UpperCAmelCase			:	Dict										=		sd_pipe(
								    **__A		,      prompt_embeds=__A		,      negative_prompt_embeds=__A		,      pooled_prompt_embeds=__A		,      negative_pooled_prompt_embeds=__A		,      )
								UpperCAmelCase			:	Tuple										=		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      :					List[str]		)      ->		Tuple:
								super().test_attention_slicing_forward_pass(expected_max_diff=3E-3		)







	def 					A     (						self      :					Dict		)      ->		Any:
								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      :					int		)      ->		Union[str, Any]:
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()







	def 					A     (						self      :					Tuple		,      __snake_case      :					str		,      __snake_case      :					Tuple="cpu"		,      __snake_case      :					List[Any]=torch.floataa		,      __snake_case      :					Union[str, Any]=0		)      ->		List[str]:
								UpperCAmelCase			:	Tuple										=		torch.Generator(device=__A		).manual_seed(__A		)
								UpperCAmelCase			:	str										=		np.random.RandomState(__A		).standard_normal((1, 4, 64, 64)		)
								UpperCAmelCase			:	Dict										=		torch.from_numpy(__A		).to(device=__A		,      dtype=__A		)
								UpperCAmelCase			:	Tuple										=		{
								    "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      :					Optional[int]		)      ->		Union[str, Any]:
								UpperCAmelCase			:	Union[str, Any]										=		DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''		)
								pipe.to(__A		)
								pipe.set_progress_bar_config(disable=__A		)

								UpperCAmelCase			:	Optional[Any]										=		self.get_inputs(__A		)
								UpperCAmelCase			:	int										=		pipe(**__A		).images
								UpperCAmelCase			:	Dict										=		image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 512, 512, 3)
								UpperCAmelCase			:	Optional[Any]										=		np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]		)
								assert np.abs(image_slice - expected_slice		).max() < 7E-3










'''simple docstring'''






from __future__ import annotations


def 			snake_case_					( _lowerCAmelCase  :						list[int]       ,				_lowerCAmelCase  :						int  )				->       list[int]:
							UpperCAmelCase			:	dict[int, int]										=		{}
							for index, val in enumerate(_lowerCAmelCase  ):
														UpperCAmelCase			:	Tuple										=		target - val
														if compl in chk_map:
																					return [chk_map[compl], index]
														UpperCAmelCase			:	Any										=		index
							return []


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						print(F"{two_sum([2, 7, 11, 15], 9) = }")





