



"""simple docstring"""
import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
      import onnxruntime as ort



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__      ,			unittest.TestCase ):
   __lowerCAmelCase  :   List[str]						=						'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE=0						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					Any	=	floats_tensor((1, 3, 128, 128)      ,     rng=random.Random(_SCREAMING_SNAKE_CASE						)						)
    UpperCAmelCase	:					Optional[int]	=	np.random.RandomState(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Union[str, Any]	=	{
        """prompt""": """A painting of a squirrel eating a burger""",
        """image""": image,
        """generator""": generator,
        """num_inference_steps""": 3,
        """strength""": 0.75,
        """guidance_scale""": 7.5,
        """output_type""": """numpy""",
    }
    return inputs

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Tuple:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Optional[int]	=	self.get_dummy_inputs()
    UpperCAmelCase	:					Union[str, Any]	=	pipe(**_SCREAMING_SNAKE_CASE						).images
    UpperCAmelCase	:					int	=	image[0, -3:, -3:, -1].flatten()

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					Union[str, Any]	=	np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087]						)
    assert np.abs(image_slice - expected_slice						).max() < 1E-1

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					List[str]	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    UpperCAmelCase	:					Optional[Any]	=	PNDMScheduler.from_config(pipe.scheduler.config      ,     skip_prk_steps=_SCREAMING_SNAKE_CASE						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Optional[int]	=	self.get_dummy_inputs()
    UpperCAmelCase	:					Optional[Any]	=	pipe(**_SCREAMING_SNAKE_CASE						).images
    UpperCAmelCase	:					int	=	image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					List[Any]	=	np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154]						)

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

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Tuple:





    '''simple docstring'''




    UpperCAmelCase	:					int	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    UpperCAmelCase	:					str	=	LMSDiscreteScheduler.from_config(pipe.scheduler.config						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    # warmup pass to apply optimizations
    UpperCAmelCase	:					Union[str, Any]	=	pipe(**self.get_dummy_inputs()						)

    UpperCAmelCase	:					Optional[int]	=	self.get_dummy_inputs()
    UpperCAmelCase	:					Tuple	=	pipe(**_SCREAMING_SNAKE_CASE						).images
    UpperCAmelCase	:					List[Any]	=	image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					Optional[int]	=	np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203]						)

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

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      str:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    UpperCAmelCase	:					Union[str, Any]	=	EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					List[str]	=	self.get_dummy_inputs()
    UpperCAmelCase	:					Any	=	pipe(**_SCREAMING_SNAKE_CASE						).images
    UpperCAmelCase	:					Dict	=	image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					int	=	np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]						)

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

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





    '''simple docstring'''




    UpperCAmelCase	:					Dict	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    UpperCAmelCase	:					Optional[int]	=	EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

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

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					List[Any]	=	np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]						)

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




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





    '''simple docstring'''




    UpperCAmelCase	:					Optional[int]	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      ,     provider="""CPUExecutionProvider"""						)
    UpperCAmelCase	:					List[str]	=	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

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

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase	:					Dict	=	np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552]						)

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



@nightly
@require_onnxruntime
@require_torch_gpu
class       SCREAMING_SNAKE_CASE__  (					unittest.TestCase ):

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Tuple:





    '''simple docstring'''




    return (
        "CUDAExecutionProvider",
        {
            "gpu_mem_limit": "15000000000",  # 15GB
            "arena_extend_strategy": "kSameAsRequested",
        },
    )

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Any:





    '''simple docstring'''




    UpperCAmelCase	:					List[str]	=	ort.SessionOptions()
    UpperCAmelCase	:					str	=	False
    return options

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





    '''simple docstring'''




    UpperCAmelCase	:					Dict	=	load_image(
        """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
        """/img2img/sketch-mountains-input.jpg"""						)
    UpperCAmelCase	:					Tuple	=	init_image.resize((768, 512)						)
    # using the PNDM scheduler by default
    UpperCAmelCase	:					str	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(
        """CompVis/stable-diffusion-v1-4"""      ,     revision="""onnx"""      ,     safety_checker=_SCREAMING_SNAKE_CASE      ,     feature_extractor=_SCREAMING_SNAKE_CASE      ,     provider=self.gpu_provider      ,     sess_options=self.gpu_options      ,     )
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Any	=	"""A fantasy landscape, trending on artstation"""

    UpperCAmelCase	:					str	=	np.random.RandomState(0						)
    UpperCAmelCase	:					str	=	pipe(
        prompt=_SCREAMING_SNAKE_CASE      ,     image=_SCREAMING_SNAKE_CASE      ,     strength=0.75      ,     guidance_scale=7.5      ,     num_inference_steps=10      ,     generator=_SCREAMING_SNAKE_CASE      ,     output_type="""np"""      ,     )
    UpperCAmelCase	:					Tuple	=	output.images
    UpperCAmelCase	:					List[Any]	=	images[0, 255:258, 383:386, -1]

    assert images.shape == (1, 512, 768, 3)
    UpperCAmelCase	:					Any	=	np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019]						)
    # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




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





    '''simple docstring'''




    UpperCAmelCase	:					Optional[Any]	=	load_image(
        """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
        """/img2img/sketch-mountains-input.jpg"""						)
    UpperCAmelCase	:					int	=	init_image.resize((768, 512)						)
    UpperCAmelCase	:					int	=	LMSDiscreteScheduler.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""      ,     subfolder="""scheduler"""      ,     revision="""onnx"""						)
    UpperCAmelCase	:					Any	=	OnnxStableDiffusionImgaImgPipeline.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""      ,     revision="""onnx"""      ,     scheduler=_SCREAMING_SNAKE_CASE      ,     safety_checker=_SCREAMING_SNAKE_CASE      ,     feature_extractor=_SCREAMING_SNAKE_CASE      ,     provider=self.gpu_provider      ,     sess_options=self.gpu_options      ,     )
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Union[str, Any]	=	"""A fantasy landscape, trending on artstation"""

    UpperCAmelCase	:					List[str]	=	np.random.RandomState(0						)
    UpperCAmelCase	:					Any	=	pipe(
        prompt=_SCREAMING_SNAKE_CASE      ,     image=_SCREAMING_SNAKE_CASE      ,     strength=0.75      ,     guidance_scale=7.5      ,     num_inference_steps=20      ,     generator=_SCREAMING_SNAKE_CASE      ,     output_type="""np"""      ,     )
    UpperCAmelCase	:					List[str]	=	output.images
    UpperCAmelCase	:					Dict	=	images[0, 255:258, 383:386, -1]

    assert images.shape == (1, 512, 768, 3)
    UpperCAmelCase	:					Tuple	=	np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431]						)
    # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import 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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


lowerCamelCase__          =		False







@skip_mps
class      A__							(     __magic_name__						,   __magic_name__						,   __magic_name__						,   unittest.TestCase	):
				lowercase			    =  StableDiffusionAttendAndExcitePipeline
				lowercase			    =  False
				lowercase			    =  TEXT_TO_IMAGE_PARAMS
				lowercase			    =  TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'}	)
				lowercase			    =  TEXT_TO_IMAGE_IMAGE_PARAMS
				lowercase			    =  TEXT_TO_IMAGE_IMAGE_PARAMS






				@classmethod
				def 							_lowerCamelCase		(						cls					:      Tuple   ):






							'''simple docstring'''







							super().setUpClass()
							torch.use_deterministic_algorithms(a   )






				@classmethod
				def 							_lowerCamelCase		(						cls					:      Any   ):






							'''simple docstring'''







							super().tearDownClass()
							torch.use_deterministic_algorithms(a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							torch.manual_seed(0   )
							lowerCAmelCase__      :      Any         =		UNetaDConditionModel(
							    block_out_channels=(32, 64)    ,     layers_per_block=1    ,     sample_size=32    ,     in_channels=4    ,     out_channels=4    ,     down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,     up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,     cross_attention_dim=32    ,     attention_head_dim=(2, 4)    ,     use_linear_projection=a    ,     )
							lowerCAmelCase__      :      Any         =		DDIMScheduler(
							    beta_start=0.0_0_0_8_5    ,     beta_end=0.0_1_2    ,     beta_schedule='scaled_linear'    ,     clip_sample=a    ,     set_alpha_to_one=a    ,     )
							torch.manual_seed(0   )
							lowerCAmelCase__      :      Union[str, Any]         =		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__      :      Tuple         =		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=1_000    ,     hidden_act='gelu'    ,     projection_dim=512    ,     )
							lowerCAmelCase__      :      str         =		CLIPTextModel(a   )
							lowerCAmelCase__      :      Optional[Any]         =		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )

							lowerCAmelCase__      :      Union[str, Any]         =		{
							    'unet': unet,
							    'scheduler': scheduler,
							    'vae': vae,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'safety_checker': None,
							    'feature_extractor': None,
							}

							return components






				def 							_lowerCamelCase		(						self					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      Union[str, Any]=0   ):






							'''simple docstring'''







							if str(a   ).startswith('mps'   ):
										lowerCAmelCase__      :      List[str]         =		torch.manual_seed(a   )
							else:
										lowerCAmelCase__      :      Any         =		torch.Generator(device=a   ).manual_seed(a   )
							lowerCAmelCase__      :      Optional[int]         =		{
							    'prompt': 'a cat and a frog',
							    'token_indices': [2, 5],
							    'generator': generator,
							    'num_inference_steps': 1,
							    'guidance_scale': 6.0,
							    'output_type': 'numpy',
							    'max_iter_to_alter': 2,
							    'thresholds': {0: 0.7},
							}
							return inputs






				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Tuple         =		'cpu'

							lowerCAmelCase__      :      Optional[int]         =		self.get_dummy_components()
							lowerCAmelCase__      :      Dict         =		self.pipeline_class(**a   )
							pipe.to(a   )
							pipe.set_progress_bar_config(disable=a   )

							lowerCAmelCase__      :      Union[str, Any]         =		self.get_dummy_inputs(a   )
							lowerCAmelCase__      :      Union[str, Any]         =		pipe(**a   ).images
							lowerCAmelCase__      :      Optional[int]         =		image[0, -3:, -3:, -1]

							self.assertEqual(image.shape    ,     (1, 64, 64, 3)   )
							lowerCAmelCase__      :      Dict         =		np.array(
							    [0.6_3_9_0_5_3_6_4, 0.6_2_8_9_7_3_0_7, 0.4_8_5_9_9_0_1_7, 0.5_1_3_3_6_2_4, 0.5_5_5_0_0_4_8, 0.4_5_7_6_9_5_1_6, 0.5_0_3_2_6_9_7_3, 0.5_0_2_3_1_3_9, 0.4_5_3_8_4_4_9_6]   )
							lowerCAmelCase__      :      Optional[int]         =		np.abs(image_slice.flatten() - expected_slice   ).max()
							self.assertLessEqual(a    ,     1E-3   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							super().test_cpu_offload_forward_pass(expected_max_diff=5E-4   )






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







							self._test_inference_batch_consistent(batch_sizes=[1, 2]   )






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							self._test_inference_batch_single_identical(batch_size=2    ,     expected_max_diff=7E-4   )






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3   )






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







							super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4   )






				def 							_lowerCamelCase		(						self					:      Any   ):






							'''simple docstring'''







							super().test_save_load_local(expected_max_difference=5E-4   )






				def 							_lowerCamelCase		(						self					:      Dict   ):






							'''simple docstring'''







							super().test_save_load_optional_components(expected_max_difference=4E-4   )







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






				@classmethod
				def 							_lowerCamelCase		(						cls					:      List[str]   ):






							'''simple docstring'''







							super().setUpClass()
							torch.use_deterministic_algorithms(a   )






				@classmethod
				def 							_lowerCamelCase		(						cls					:      List[str]   ):






							'''simple docstring'''







							super().tearDownClass()
							torch.use_deterministic_algorithms(a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		torch.manual_seed(51   )

							lowerCAmelCase__      :      Any         =		StableDiffusionAttendAndExcitePipeline.from_pretrained(
							    'CompVis/stable-diffusion-v1-4'    ,     safety_checker=a    ,     torch_dtype=torch.floataa   )
							pipe.to('cuda'   )

							lowerCAmelCase__      :      Optional[int]         =		'a painting of an elephant with glasses'
							lowerCAmelCase__      :      Any         =		[5, 7]

							lowerCAmelCase__      :      Optional[Any]         =		pipe(
							    prompt=a    ,     token_indices=a    ,     guidance_scale=7.5    ,     generator=a    ,     num_inference_steps=5    ,     max_iter_to_alter=5    ,     output_type='numpy'    ,     ).images[0]

							lowerCAmelCase__      :      str         =		load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'   )
							assert np.abs((expected_image - image).max()   ) < 5E-1