



"""simple docstring"""






import gc
import random
import unittest

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

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

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class 			A__   (  __SCREAMING_SNAKE_CASE  ,		__SCREAMING_SNAKE_CASE  ,		unittest.TestCase							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	StableDiffusionXLImgaImgPipeline
	SCREAMING_SNAKE_CASE          =	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
	SCREAMING_SNAKE_CASE          =	PipelineTesterMixin.required_optional_params - {'latents'}
	SCREAMING_SNAKE_CASE          =	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	SCREAMING_SNAKE_CASE          =	IMAGE_TO_IMAGE_IMAGE_PARAMS
	SCREAMING_SNAKE_CASE          =	IMAGE_TO_IMAGE_IMAGE_PARAMS

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

				"""simple docstring"""

				torch.manual_seed(0)
				__lowerCAmelCase      :  List[Any]												=       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       ,			)
				__lowerCAmelCase      :  Tuple												=       EulerDiscreteScheduler(
				    beta_start=0.0_0085       ,			beta_end=0.012       ,			steps_offset=1       ,			beta_schedule="scaled_linear"       ,			timestep_spacing="leading"       ,			)
				torch.manual_seed(0)
				__lowerCAmelCase      :  str												=       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)
				__lowerCAmelCase      :  Optional[int]												=       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       ,			)
				__lowerCAmelCase      :  List[Any]												=       CLIPTextModel(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  List[Any]												=       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       ,			local_files_only=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Optional[Any]												=       CLIPTextModelWithProjection(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  int												=       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       ,			local_files_only=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  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 							_SCREAMING_SNAKE_CASE   (     self:		int       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Any=0)				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       floats_tensor((1, 3, 32, 32)       ,			rng=random.Random(_SCREAMING_SNAKE_CASE)).to(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  List[Any]												=       image / 2 + 0.5
				if str(_SCREAMING_SNAKE_CASE).startswith("mps"):
							__lowerCAmelCase      :  int												=       torch.manual_seed(_SCREAMING_SNAKE_CASE)
				else:
							__lowerCAmelCase      :  Any												=       torch.Generator(device=_SCREAMING_SNAKE_CASE).manual_seed(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  int												=       {
				    "prompt": "A painting of a squirrel eating a burger",
				    "image": image,
				    "generator": generator,
				    "num_inference_steps": 2,
				    "guidance_scale": 5.0,
				    "output_type": "numpy",
				    "strength": 0.75,
				}
				return inputs

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple)				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       "cpu"  # ensure determinism for the device-dependent torch.Generator
				__lowerCAmelCase      :  Optional[Any]												=       self.get_dummy_components()
				__lowerCAmelCase      :  List[Any]												=       StableDiffusionXLImgaImgPipeline(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  int												=       sd_pipe.to(_SCREAMING_SNAKE_CASE)
				sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  List[Any]												=       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Union[str, Any]												=       sd_pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  str												=       image[0, -3:, -3:, -1]

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

				__lowerCAmelCase      :  int												=       np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       Dict:

				"""simple docstring"""

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

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

				"""simple docstring"""

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

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

				"""simple docstring"""

				pass







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

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       self.get_dummy_components()
				__lowerCAmelCase      :  str												=       StableDiffusionXLImgaImgPipeline(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Dict												=       sd_pipe.to(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  int												=       sd_pipe.to(_SCREAMING_SNAKE_CASE)
				sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				# forward without prompt embeds
				__lowerCAmelCase      :  str												=       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  str												=       3 * ["this is a negative prompt"]
				__lowerCAmelCase      :  Union[str, Any]												=       negative_prompt
				__lowerCAmelCase      :  Optional[int]												=       3 * [inputs["prompt"]]

				__lowerCAmelCase      :  Dict												=       sd_pipe(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Union[str, Any]												=       output.images[0, -3:, -3:, -1]

				# forward with prompt embeds
				__lowerCAmelCase      :  Union[str, Any]												=       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Optional[Any]												=       3 * ["this is a negative prompt"]
				__lowerCAmelCase      :  List[str]												=       3 * [inputs.pop("prompt")]

				(
				    (
				    __lowerCAmelCase
				)						,	(
				    __lowerCAmelCase
				)						,	(
				    __lowerCAmelCase
				)						,	(
				    __lowerCAmelCase
				)						,	
				)      :  Optional[Any]												=       sd_pipe.encode_prompt(_SCREAMING_SNAKE_CASE       ,			negative_prompt=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  str												=       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       ,			)
				__lowerCAmelCase      :  Dict												=       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






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




	'''simple docstring'''





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

				"""simple docstring"""

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		str="cpu"       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=torch.floataa       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=0)				->       Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase      :  Tuple												=       torch.Generator(device=_SCREAMING_SNAKE_CASE).manual_seed(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Any												=       np.random.RandomState(_SCREAMING_SNAKE_CASE).standard_normal((1, 4, 64, 64))
				__lowerCAmelCase      :  Tuple												=       torch.from_numpy(_SCREAMING_SNAKE_CASE).to(device=_SCREAMING_SNAKE_CASE       ,			dtype=_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Optional[int]												=       {
				    "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:		Union[str, Any])				->       Any:

				"""simple docstring"""

				__lowerCAmelCase      :  Union[str, Any]												=       DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")
				pipe.to(_SCREAMING_SNAKE_CASE)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				assert image.shape == (1, 512, 512, 3)
				__lowerCAmelCase      :  Union[str, Any]												=       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




"""simple docstring"""






def 			_lowercase				(  __snake_case					,__snake_case	)						->   float:
			if digit_amount > 0:
						return round(number - int(__snake_case	)					,__snake_case	)
			return number - int(__snake_case	)


if __name__ == "__main__":
	print(decimal_isolate(1.53, 0))
	print(decimal_isolate(35.345, 1))
	print(decimal_isolate(35.345, 2))
	print(decimal_isolate(35.345, 3))
	print(decimal_isolate(-14.789, 3))
	print(decimal_isolate(0, 2))
	print(decimal_isolate(-14.123, 1))
	print(decimal_isolate(-14.123, 2))
	print(decimal_isolate(-14.123, 3))