




"""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 _lowerCamelCase				(     UpperCamelCase__   ,       unittest.TestCase						):
   _lowerCamelCase				:List[Any]	      =	"hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"






   def        _lowerCAmelCase    (		self   :		Optional[int]    ,	UpperCamelCase   :		Tuple=0    ) ->						Optional[Any]:

         """simple docstring"""
         lowerCAmelCase__			: Tuple  					=       floats_tensor((1, 3, 1_28, 1_28)    ,	rng=random.Random(_a    )    )
         lowerCAmelCase__			: Optional[Any]  					=       np.random.RandomState(_a    )
         lowerCAmelCase__			: Optional[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        _lowerCAmelCase    (		self   :		Optional[int]    ) ->						int:

         """simple docstring"""
         lowerCAmelCase__			: int  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         pipe.set_progress_bar_config(disable=_a    )

         lowerCAmelCase__			: Any  					=       self.get_dummy_inputs()
         lowerCAmelCase__			: List[str]  					=       pipe(**_a    ).images
         lowerCAmelCase__			: Optional[Any]  					=       image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: List[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        _lowerCAmelCase    (		self   :		int    ) ->						Dict:

         """simple docstring"""
         lowerCAmelCase__			: List[Any]  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         lowerCAmelCase__			: List[Any]  					=       PNDMScheduler.from_config(pipe.scheduler.config    ,	skip_prk_steps=_a    )
         pipe.set_progress_bar_config(disable=_a    )

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

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: Dict  					=       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        _lowerCAmelCase    (		self   :		List[Any]    ) ->						List[Any]:

         """simple docstring"""
         lowerCAmelCase__			: Dict  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         lowerCAmelCase__			: Tuple  					=       LMSDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=_a    )

         # warmup pass to apply optimizations
         lowerCAmelCase__			: List[Any]  					=       pipe(**self.get_dummy_inputs()    )

         lowerCAmelCase__			: Tuple  					=       self.get_dummy_inputs()
         lowerCAmelCase__			: List[str]  					=       pipe(**_a    ).images
         lowerCAmelCase__			: Optional[Any]  					=       image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: Dict  					=       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        _lowerCAmelCase    (		self   :		Optional[int]    ) ->						Union[str, Any]:

         """simple docstring"""
         lowerCAmelCase__			: str  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         lowerCAmelCase__			: Any  					=       EulerDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=_a    )

         lowerCAmelCase__			: int  					=       self.get_dummy_inputs()
         lowerCAmelCase__			: Tuple  					=       pipe(**_a    ).images
         lowerCAmelCase__			: Any  					=       image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: 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        _lowerCAmelCase    (		self   :		List[str]    ) ->						List[Any]:

         """simple docstring"""
         lowerCAmelCase__			: int  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         lowerCAmelCase__			: Union[str, Any]  					=       EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=_a    )

         lowerCAmelCase__			: Optional[Any]  					=       self.get_dummy_inputs()
         lowerCAmelCase__			: Tuple  					=       pipe(**_a    ).images
         lowerCAmelCase__			: Any  					=       image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: str  					=       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        _lowerCAmelCase    (		self   :		Optional[Any]    ) ->						List[str]:

         """simple docstring"""
         lowerCAmelCase__			: Union[str, Any]  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint    ,	provider="""CPUExecutionProvider"""    )
         lowerCAmelCase__			: str  					=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=_a    )

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

         assert image.shape == (1, 1_28, 1_28, 3)
         lowerCAmelCase__			: Optional[int]  					=       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 _lowerCamelCase				(     unittest.TestCase						):






   @property
   def        _lowerCAmelCase    (		self   :		Tuple    ) ->						str:

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






   @property
   def        _lowerCAmelCase    (		self   :		Dict    ) ->						Optional[int]:

         """simple docstring"""
         lowerCAmelCase__			: Union[str, Any]  					=       ort.SessionOptions()
         lowerCAmelCase__			: List[str]  					=       False
         return options






   def        _lowerCAmelCase    (		self   :		str    ) ->						Tuple:

         """simple docstring"""
         lowerCAmelCase__			: str  					=       load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
             """/img2img/sketch-mountains-input.jpg"""    )
         lowerCAmelCase__			: Optional[Any]  					=       init_image.resize((7_68, 5_12)    )
         # using the PNDM scheduler by default
         lowerCAmelCase__			: List[str]  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""    ,	revision="""onnx"""    ,	safety_checker=_a    ,	feature_extractor=_a    ,	provider=self.gpu_provider    ,	sess_options=self.gpu_options    ,	)
         pipe.set_progress_bar_config(disable=_a    )

         lowerCAmelCase__			: str  					=       """A fantasy landscape, trending on artstation"""

         lowerCAmelCase__			: List[str]  					=       np.random.RandomState(0    )
         lowerCAmelCase__			: Dict  					=       pipe(
             prompt=_a    ,	image=_a    ,	strength=0.75    ,	guidance_scale=7.5    ,	num_inference_steps=10    ,	generator=_a    ,	output_type="""np"""    ,	)
         lowerCAmelCase__			: Optional[Any]  					=       output.images
         lowerCAmelCase__			: Optional[Any]  					=       images[0, 2_55:2_58, 3_83:3_86, -1]

         assert images.shape == (1, 5_12, 7_68, 3)
         lowerCAmelCase__			: Optional[int]  					=       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        _lowerCAmelCase    (		self   :		int    ) ->						Optional[Any]:

         """simple docstring"""
         lowerCAmelCase__			: Any  					=       load_image(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
             """/img2img/sketch-mountains-input.jpg"""    )
         lowerCAmelCase__			: Union[str, Any]  					=       init_image.resize((7_68, 5_12)    )
         lowerCAmelCase__			: Any  					=       LMSDiscreteScheduler.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""    ,	subfolder="""scheduler"""    ,	revision="""onnx"""    )
         lowerCAmelCase__			: int  					=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""    ,	revision="""onnx"""    ,	scheduler=_a    ,	safety_checker=_a    ,	feature_extractor=_a    ,	provider=self.gpu_provider    ,	sess_options=self.gpu_options    ,	)
         pipe.set_progress_bar_config(disable=_a    )

         lowerCAmelCase__			: str  					=       """A fantasy landscape, trending on artstation"""

         lowerCAmelCase__			: int  					=       np.random.RandomState(0    )
         lowerCAmelCase__			: Optional[Any]  					=       pipe(
             prompt=_a    ,	image=_a    ,	strength=0.75    ,	guidance_scale=7.5    ,	num_inference_steps=20    ,	generator=_a    ,	output_type="""np"""    ,	)
         lowerCAmelCase__			: Tuple  					=       output.images
         lowerCAmelCase__			: List[Any]  					=       images[0, 2_55:2_58, 3_83:3_86, -1]

         assert images.shape == (1, 5_12, 7_68, 3)
         lowerCAmelCase__			: List[Any]  					=       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 torch

from diffusers import DPMSolverSDEScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import require_torchsde

from .test_schedulers import SchedulerCommonTest







@require_torchsde
class 						lowercase							(   UpperCamelCase__		):
     _a							 =						(DPMSolverSDEScheduler,)
     _a							 =						1_0

     def 					a__	(  self		,     **_a				)						->							Optional[Any]:
           _A							:     str			=						{
               """num_train_timesteps""": 1100,
               """beta_start""": 0.0001,
               """beta_end""": 0.02,
               """beta_schedule""": """linear""",
               """noise_sampler_seed""": 0,
           }

           config.update(**_a				)
           return config

     def 					a__	(  self				)						->							Tuple:
           for timesteps in [10, 50, 100, 1000]:
                 self.check_over_configs(num_train_timesteps=_a				)

     def 					a__	(  self				)						->							Optional[int]:
           for beta_start, beta_end in zip([0.00001, 0.0001, 0.001]		,     [0.0002, 0.002, 0.02]				):
                 self.check_over_configs(beta_start=_a		,     beta_end=_a				)

     def 					a__	(  self				)						->							Any:
           for schedule in ["linear", "scaled_linear"]:
                 self.check_over_configs(beta_schedule=_a				)

     def 					a__	(  self				)						->							Optional[int]:
           for prediction_type in ["epsilon", "v_prediction"]:
                 self.check_over_configs(prediction_type=_a				)

     def 					a__	(  self				)						->							Optional[int]:
           _A							:     Any			=						self.scheduler_classes[0]
           _A							:     List[str]			=						self.get_scheduler_config()
           _A							:     Optional[Any]			=						scheduler_class(**_a				)

           scheduler.set_timesteps(self.num_inference_steps				)

           _A							:     Dict			=						self.dummy_model()
           _A							:     Any			=						self.dummy_sample_deter * scheduler.init_noise_sigma
           _A							:     Dict			=						sample.to(_a				)

           for i, t in enumerate(scheduler.timesteps				):
                 _A							:     Optional[int]			=						scheduler.scale_model_input(_a		,     _a				)

                 _A							:     str			=						model(_a		,     _a				)

                 _A							:     List[Any]			=						scheduler.step(_a		,     _a		,     _a				)
                 _A							:     Optional[int]			=						output.prev_sample

           _A							:     Dict			=						torch.sum(torch.abs(_a				)				)
           _A							:     Dict			=						torch.mean(torch.abs(_a				)				)

           if torch_device in ["mps"]:
                 assert abs(result_sum.item() - 167.47821044921875				) < 1e-2
                 assert abs(result_mean.item() - 0.2178705964565277				) < 1e-3
           elif torch_device in ["cuda"]:
                 assert abs(result_sum.item() - 171.59352111816406				) < 1e-2
                 assert abs(result_mean.item() - 0.22342906892299652				) < 1e-3
           else:
                 assert abs(result_sum.item() - 162.52383422851562				) < 1e-2
                 assert abs(result_mean.item() - 0.211619570851326				) < 1e-3

     def 					a__	(  self				)						->							Optional[Any]:
           _A							:     Dict			=						self.scheduler_classes[0]
           _A							:     Optional[int]			=						self.get_scheduler_config(prediction_type="""v_prediction"""				)
           _A							:     Optional[Any]			=						scheduler_class(**_a				)

           scheduler.set_timesteps(self.num_inference_steps				)

           _A							:     Tuple			=						self.dummy_model()
           _A							:     int			=						self.dummy_sample_deter * scheduler.init_noise_sigma
           _A							:     Tuple			=						sample.to(_a				)

           for i, t in enumerate(scheduler.timesteps				):
                 _A							:     int			=						scheduler.scale_model_input(_a		,     _a				)

                 _A							:     Tuple			=						model(_a		,     _a				)

                 _A							:     Dict			=						scheduler.step(_a		,     _a		,     _a				)
                 _A							:     Optional[int]			=						output.prev_sample

           _A							:     Optional[Any]			=						torch.sum(torch.abs(_a				)				)
           _A							:     List[Any]			=						torch.mean(torch.abs(_a				)				)

           if torch_device in ["mps"]:
                 assert abs(result_sum.item() - 124.77149200439453				) < 1e-2
                 assert abs(result_mean.item() - 0.16226289014816284				) < 1e-3
           elif torch_device in ["cuda"]:
                 assert abs(result_sum.item() - 128.1663360595703				) < 1e-2
                 assert abs(result_mean.item() - 0.16688326001167297				) < 1e-3
           else:
                 assert abs(result_sum.item() - 119.8487548828125				) < 1e-2
                 assert abs(result_mean.item() - 0.1560530662536621				) < 1e-3

     def 					a__	(  self				)						->							List[str]:
           _A							:     Union[str, Any]			=						self.scheduler_classes[0]
           _A							:     List[Any]			=						self.get_scheduler_config()
           _A							:     List[str]			=						scheduler_class(**_a				)

           scheduler.set_timesteps(self.num_inference_steps		,     device=_a				)

           _A							:     Union[str, Any]			=						self.dummy_model()
           _A							:     Optional[Any]			=						self.dummy_sample_deter.to(_a				) * scheduler.init_noise_sigma

           for t in scheduler.timesteps:
                 _A							:     int			=						scheduler.scale_model_input(_a		,     _a				)

                 _A							:     List[Any]			=						model(_a		,     _a				)

                 _A							:     Dict			=						scheduler.step(_a		,     _a		,     _a				)
                 _A							:     Dict			=						output.prev_sample

           _A							:     str			=						torch.sum(torch.abs(_a				)				)
           _A							:     str			=						torch.mean(torch.abs(_a				)				)

           if torch_device in ["mps"]:
                 assert abs(result_sum.item() - 167.46957397460938				) < 1e-2
                 assert abs(result_mean.item() - 0.21805934607982635				) < 1e-3
           elif torch_device in ["cuda"]:
                 assert abs(result_sum.item() - 171.59353637695312				) < 1e-2
                 assert abs(result_mean.item() - 0.22342908382415771				) < 1e-3
           else:
                 assert abs(result_sum.item() - 162.52383422851562				) < 1e-2
                 assert abs(result_mean.item() - 0.211619570851326				) < 1e-3



     def 					a__	(  self				)						->							Union[str, Any]:
           _A							:     List[Any]			=						self.scheduler_classes[0]
           _A							:     Optional[Any]			=						self.get_scheduler_config()
           _A							:     int			=						scheduler_class(**_a		,     use_karras_sigmas=_a				)

           scheduler.set_timesteps(self.num_inference_steps		,     device=_a				)

           _A							:     Optional[Any]			=						self.dummy_model()
           _A							:     Dict			=						self.dummy_sample_deter.to(_a				) * scheduler.init_noise_sigma
           _A							:     str			=						sample.to(_a				)

           for t in scheduler.timesteps:
                 _A							:     Optional[int]			=						scheduler.scale_model_input(_a		,     _a				)

                 _A							:     List[Any]			=						model(_a		,     _a				)

                 _A							:     Dict			=						scheduler.step(_a		,     _a		,     _a				)
                 _A							:     List[str]			=						output.prev_sample

           _A							:     str			=						torch.sum(torch.abs(_a				)				)
           _A							:     List[str]			=						torch.mean(torch.abs(_a				)				)

           if torch_device in ["mps"]:
                 assert abs(result_sum.item() - 176.66974135742188				) < 1e-2
                 assert abs(result_mean.item() - 0.23003872730981811				) < 1e-2
           elif torch_device in ["cuda"]:
                 assert abs(result_sum.item() - 177.63653564453125				) < 1e-2
                 assert abs(result_mean.item() - 0.23003872730981811				) < 1e-2
           else:
                 assert abs(result_sum.item() - 170.3135223388672				) < 1e-2
                 assert abs(result_mean.item() - 0.23003872730981811				) < 1e-2

