





'''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 		lowerCamelCase	(   _A   , _A   , unittest.TestCase							):
	snake_case_   = StableDiffusionXLImgaImgPipeline
	snake_case_   = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
	snake_case_   = PipelineTesterMixin.required_optional_params - {"latents"}
	snake_case_   = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	snake_case_   = IMAGE_TO_IMAGE_IMAGE_PARAMS
	snake_case_   = IMAGE_TO_IMAGE_IMAGE_PARAMS



	def 	_lowerCamelCase     ( self						):
			torch.manual_seed(0						)
			lowerCAmelCase  :     Union[str, 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=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		,   )
			lowerCAmelCase  :     Optional[Any]       						= EulerDiscreteScheduler(
			    beta_start=0.00085		,   beta_end=0.012		,   steps_offset=1		,   beta_schedule="scaled_linear"		,   timestep_spacing="leading"		,   )
			torch.manual_seed(0						)
			lowerCAmelCase  :     Dict       						= 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  :     Dict       						= CLIPTextConfig(
			    bos_token_id=0		,   eos_token_id=2		,   hidden_size=32		,   intermediate_size=37		,   layer_norm_eps=1e-0_5		,   num_attention_heads=4		,   num_hidden_layers=5		,   pad_token_id=1		,   vocab_size=1_000		,   hidden_act="gelu"		,   projection_dim=32		,   )
			lowerCAmelCase  :     Tuple       						= CLIPTextModel(a_						)
			lowerCAmelCase  :     Optional[Any]       						= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,   local_files_only=a_						)

			lowerCAmelCase  :     Tuple       						= CLIPTextModelWithProjection(a_						)
			lowerCAmelCase  :     int       						= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,   local_files_only=a_						)

			lowerCAmelCase  :     Union[str, 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 	_lowerCamelCase     ( self		,   a_		,   a_=0						):
			lowerCAmelCase  :     List[str]       						= floats_tensor((1, 3, 32, 32)		,   rng=random.Random(a_						)						).to(a_						)
			lowerCAmelCase  :     List[str]       						= image / 2 + 0.5
			if str(a_						).startswith("mps"						):
					lowerCAmelCase  :     str       						= torch.manual_seed(a_						)
			else:
					lowerCAmelCase  :     List[str]       						= torch.Generator(device=a_						).manual_seed(a_						)
			lowerCAmelCase  :     Union[str, Any]       						= {
			    "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 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     int       						= "cpu"  # ensure determinism for the device-dependent torch.Generator
			lowerCAmelCase  :     Union[str, Any]       						= self.get_dummy_components()
			lowerCAmelCase  :     List[str]       						= StableDiffusionXLImgaImgPipeline(**a_						)
			lowerCAmelCase  :     Optional[Any]       						= sd_pipe.to(a_						)
			sd_pipe.set_progress_bar_config(disable=a_						)

			lowerCAmelCase  :     List[Any]       						= self.get_dummy_inputs(a_						)
			lowerCAmelCase  :     Any       						= sd_pipe(**a_						).images
			lowerCAmelCase  :     Tuple       						= image[0, -3:, -3:, -1]

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

			lowerCAmelCase  :     Optional[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 	_lowerCamelCase     ( self						):
			super().test_attention_slicing_forward_pass(expected_max_diff=3e-3						)



	def 	_lowerCamelCase     ( self						):
			super().test_inference_batch_single_identical(expected_max_diff=3e-3						)



	def 	_lowerCamelCase     ( self						):
			pass





	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     List[str]       						= self.get_dummy_components()
			lowerCAmelCase  :     Tuple       						= StableDiffusionXLImgaImgPipeline(**a_						)
			lowerCAmelCase  :     int       						= sd_pipe.to(a_						)
			lowerCAmelCase  :     Optional[int]       						= sd_pipe.to(a_						)
			sd_pipe.set_progress_bar_config(disable=a_						)

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

			lowerCAmelCase  :     Optional[Any]       						= sd_pipe(**a_						)
			lowerCAmelCase  :     Any       						= output.images[0, -3:, -3:, -1]

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

			(
			    (
			    lowerCAmelCase
			)						,		(
			    lowerCAmelCase
			)						,		(
			    lowerCAmelCase
			)						,		(
			    lowerCAmelCase
			)						,		
			)  :     Dict       						= sd_pipe.encode_prompt(a_		,   negative_prompt=a_						)

			lowerCAmelCase  :     List[str]       						= sd_pipe(
			    **a_		,   prompt_embeds=a_		,   negative_prompt_embeds=a_		,   pooled_prompt_embeds=a_		,   negative_pooled_prompt_embeds=a_		,   )
			lowerCAmelCase  :     List[Any]       						= 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 		lowerCamelCase	(   unittest.TestCase							):



	def 	_lowerCamelCase     ( self						):
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()



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

			lowerCAmelCase  :     Any       						= self.get_inputs(a_						)
			lowerCAmelCase  :     Any       						= pipe(**a_						).images
			lowerCAmelCase  :     Any       						= image[0, -3:, -3:, -1].flatten()

			assert image.shape == (1, 512, 512, 3)
			lowerCAmelCase  :     Union[str, Any]       						= np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]						)
			assert np.abs(image_slice - expected_slice						).max() < 7e-3










'''simple docstring'''






import math

import tensorflow as tf
from packaging import version






def   __A    (				a_    :	List[Any]						):
		lowerCAmelCase  :     Any       						= tf.convert_to_tensor(a_						)
		lowerCAmelCase  :     List[Any]       						= 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0						)   ,x.dtype						)						))

		return x * cdf






def   __A    (				a_    :	int						):
		lowerCAmelCase  :     Dict       						= tf.convert_to_tensor(a_						)
		lowerCAmelCase  :     int       						= tf.cast(math.pi   ,x.dtype						)
		lowerCAmelCase  :     Dict       						= tf.cast(0.0_4_4_7_1_5   ,x.dtype						)
		lowerCAmelCase  :     Dict       						= 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi						) * (x + coeff * tf.pow(a_   ,3						))						))

		return x * cdf






def   __A    (				a_    :	Union[str, Any]						):
		lowerCAmelCase  :     Any       						= tf.convert_to_tensor(a_						)

		return x * tf.tanh(tf.math.softplus(a_						)						)






def   __A    (				a_    :	List[str]						):
		lowerCAmelCase  :     Dict       						= tf.convert_to_tensor(a_						)
		lowerCAmelCase  :     Any       						= tf.cast(0.0_4_4_7_1_5   ,x.dtype						)
		lowerCAmelCase  :     Optional[int]       						= tf.cast(0.7_9_7_8_8_4_5_6_0_8   ,x.dtype						)

		return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x)						))






def   __A    (				a_    :	Union[str, Any]						):
		lowerCAmelCase  :     Optional[int]       						= tf.convert_to_tensor(a_						)
		lowerCAmelCase  :     List[Any]       						= tf.cast(1.7_0_2   ,x.dtype						)
		return x * tf.math.sigmoid(coeff * x						)






def   __A    (				a_    :	List[Any]						):
		return tf.clip_by_value(_gelu(a_						)   ,-1_0   ,1_0						)






def   __A    (				a_    :	List[Any]   ,a_    :	List[Any]=-1						):
		lowerCAmelCase						,		lowerCAmelCase  :     Optional[int]       						= tf.split(a_   ,2   ,axis=a_						)
		return a * tf.math.sigmoid(a_						)


if version.parse(tf.version.VERSION) >= version.parse("""2.4"""):






					def   __A    (				a_    :	Optional[Any]						):
							return tf.keras.activations.gelu(a_   ,approximate=a_						)

					lowerCAmelCase									=   tf.keras.activations.gelu

					lowerCAmelCase									=   approximate_gelu_wrap
else:
					lowerCAmelCase									=   _gelu
					lowerCAmelCase									=   _gelu_new


lowerCAmelCase									=   {
    """gelu""": gelu,
    """gelu_10""": gelu_aa,
    """gelu_fast""": gelu_fast,
    """gelu_new""": gelu_new,
    """glu""": glu,
    """mish""": mish,
    """quick_gelu""": quick_gelu,
    """relu""": tf.keras.activations.relu,
    """sigmoid""": tf.keras.activations.sigmoid,
    """silu""": tf.keras.activations.swish,
    """swish""": tf.keras.activations.swish,
    """tanh""": tf.keras.activations.tanh,
}






def   __A    (				a_    :	int						):
		if activation_string in ACTaFN:
				return ACTaFN[activation_string]
		else:
				raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()						)}'''						)



