"""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  _snake_case     (					a__				, unittest.TestCase		):
						snake_case__			  =			"hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"






						def       lowerCamelCase__     (       self      :			Tuple							,					UpperCAmelCase      :			Optional[int]=0    ):
													__lowerCamelCase					:		Optional[int]		   =     floats_tensor((1, 3, 128, 128)							,					rng=random.Random(UpperCAmelCase    )    )
													__lowerCamelCase					:		List[Any]		   =     np.random.RandomState(UpperCAmelCase    )
													__lowerCamelCase					:		Optional[Any]		   =     {
													    "prompt": "A painting of a squirrel eating a burger",
													    "image": image,
													    "generator": generator,
													    "num_inference_steps": 3,
													    "strength": 0.7_5,
													    "guidance_scale": 7.5,
													    "output_type": "numpy",
													}
													return inputs






						def       lowerCamelCase__     (       self      :			int    ):
													__lowerCamelCase					:		Any		   =     OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,					provider="CPUExecutionProvider"    )
													pipe.set_progress_bar_config(disable=UpperCAmelCase    )

													__lowerCamelCase					:		Tuple		   =     self.get_dummy_inputs()
													__lowerCamelCase					:		Tuple		   =     pipe(**UpperCAmelCase    ).images
													__lowerCamelCase					:		str		   =     image[0, -3:, -3:, -1].flatten()

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		Any		   =     np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7]    )
													assert np.abs(image_slice - expected_slice    ).max() < 1E-1






						def       lowerCamelCase__     (       self      :			Optional[int]    ):
													__lowerCamelCase					:		Union[str, Any]		   =     OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,					provider="CPUExecutionProvider"    )
													__lowerCamelCase					:		int		   =     PNDMScheduler.from_config(pipe.scheduler.config							,					skip_prk_steps=UpperCAmelCase    )
													pipe.set_progress_bar_config(disable=UpperCAmelCase    )

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

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		Dict		   =     np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4]    )

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






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

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

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

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		Tuple		   =     np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3]    )

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






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

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

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		List[str]		   =     np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4]    )

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






						def       lowerCamelCase__     (       self      :			List[str]    ):
													__lowerCamelCase					:		Any		   =     OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,					provider="CPUExecutionProvider"    )
													__lowerCamelCase					:		str		   =     EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
													pipe.set_progress_bar_config(disable=UpperCAmelCase    )

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

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		Optional[Any]		   =     np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4]    )

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







						def       lowerCamelCase__     (       self      :			List[Any]    ):
													__lowerCamelCase					:		List[str]		   =     OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,					provider="CPUExecutionProvider"    )
													__lowerCamelCase					:		List[Any]		   =     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
													pipe.set_progress_bar_config(disable=UpperCAmelCase    )

													__lowerCamelCase					:		int		   =     self.get_dummy_inputs()
													__lowerCamelCase					:		Tuple		   =     pipe(**UpperCAmelCase    ).images
													__lowerCamelCase					:		Dict		   =     image[0, -3:, -3:, -1]

													assert image.shape == (1, 128, 128, 3)
													__lowerCamelCase					:		int		   =     np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2]    )

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

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






						@property
						def       lowerCamelCase__     (       self      :			Union[str, Any]    ):
													return (
													    "CUDAExecutionProvider",
													    {
													        "gpu_mem_limit": "15000000000",  # 15GB
													        "arena_extend_strategy": "kSameAsRequested",
													    },
													)






						@property
						def       lowerCamelCase__     (       self      :			Any    ):
													__lowerCamelCase					:		Tuple		   =     ort.SessionOptions()
													__lowerCamelCase					:		Optional[int]		   =     False
													return options






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

													__lowerCamelCase					:		int		   =     "A fantasy landscape, trending on artstation"

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

													assert images.shape == (1, 512, 768, 3)
													__lowerCamelCase					:		Optional[Any]		   =     np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9]    )
													# 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      :			Union[str, Any]    ):
													__lowerCamelCase					:		Dict		   =     load_image(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
													    "/img2img/sketch-mountains-input.jpg"    )
													__lowerCamelCase					:		Dict		   =     init_image.resize((768, 512)    )
													__lowerCamelCase					:		List[str]		   =     LMSDiscreteScheduler.from_pretrained(
													    "runwayml/stable-diffusion-v1-5"							,					subfolder="scheduler"							,					revision="onnx"    )
													__lowerCamelCase					:		List[str]		   =     OnnxStableDiffusionImgaImgPipeline.from_pretrained(
													    "runwayml/stable-diffusion-v1-5"							,					revision="onnx"							,					scheduler=UpperCAmelCase							,					safety_checker=UpperCAmelCase							,					feature_extractor=UpperCAmelCase							,					provider=self.gpu_provider							,					sess_options=self.gpu_options							,					)
													pipe.set_progress_bar_config(disable=UpperCAmelCase    )

													__lowerCamelCase					:		List[str]		   =     "A fantasy landscape, trending on artstation"

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

													assert images.shape == (1, 512, 768, 3)
													__lowerCamelCase					:		str		   =     np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1]    )
													# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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





import gc
import threading
import time

import psutil
import torch
class  _snake_case     :






						def __init__(       self      :			str    ):
													__lowerCamelCase					:		Optional[Any]		   =     psutil.Process()
													__lowerCamelCase					:		List[Any]		   =     False






						def       lowerCamelCase__     (       self      :			str    ):
													__lowerCamelCase					:		List[Any]		   =     -1

													while True:
																				__lowerCamelCase					:		Union[str, Any]		   =     max(self.process.memory_info().rss							,					self.cpu_memory_peak    )

																				# can't sleep or will not catch the peak right (this comment is here on purpose)
																				if not self.peak_monitoring:
																											break






						def       lowerCamelCase__     (       self      :			Any    ):
													__lowerCamelCase					:		Optional[Any]		   =     True
													__lowerCamelCase					:		Union[str, Any]		   =     threading.Thread(target=self.peak_monitor    )
													__lowerCamelCase					:		Optional[Any]		   =     True
													self.thread.start()







						def       lowerCamelCase__     (       self      :			Dict    ):
													__lowerCamelCase					:		str		   =     False
													self.thread.join()
													return self.cpu_memory_peak

__A  =				PeakCPUMemory()


def    lowercase_   (   ) ->      Union[str, Any]:



							'''simple docstring'''

							__lowerCamelCase					:		Any		   =     {"time": time.time()}

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

							# CPU mem
							__lowerCamelCase					:		Optional[int]		   =     psutil.Process().memory_info().rss
							cpu_peak_tracker.start()

							# GPU mem
							for i in range(torch.cuda.device_count()      ):
														__lowerCamelCase					:		int		   =     torch.cuda.memory_allocated(_lowerCamelCase      )
							torch.cuda.reset_peak_memory_stats()

							return measures


def    lowercase_   (   _lowerCamelCase:	Optional[Any]      ) ->      Tuple:



							'''simple docstring'''

							__lowerCamelCase					:		Tuple		   =     {"time": time.time() - start_measures["time"]}

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

							# CPU mem
							__lowerCamelCase					:		Dict		   =     (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20
							__lowerCamelCase					:		Tuple		   =     (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20

							# GPU mem
							for i in range(torch.cuda.device_count()      ):
														__lowerCamelCase					:		Any		   =     (torch.cuda.memory_allocated(_lowerCamelCase      ) - start_measures[str(_lowerCamelCase      )]) / 2**20
														__lowerCamelCase					:		Optional[int]		   =     (torch.cuda.max_memory_allocated(_lowerCamelCase      ) - start_measures[str(_lowerCamelCase      )]) / 2**20

							return measures







def    lowercase_   (   _lowerCamelCase:	int						,   _lowerCamelCase:	List[Any]      ) ->      Optional[int]:



							'''simple docstring'''

							print(F"""{description}:"""      )
							print(F"""- Time: {measures["time"]:.2f}s"""      )
							for i in range(torch.cuda.device_count()      ):
														print(F"""- GPU {i} allocated: {measures[str(_lowerCamelCase      )]:.2f}MiB"""      )
														__lowerCamelCase					:		List[Any]		   =     measures[F"""{i}-peak"""]
														print(F"""- GPU {i} peak: {peak:.2f}MiB"""      )
							print(F"""- CPU RAM allocated: {measures["cpu"]:.2f}MiB"""      )
							print(F"""- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB"""      )