

"""simple docstring"""


import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    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     (    __snake_case,							unittest.TestCase  ):
				# TODO: is there an appropriate internal test set?
				SCREAMING_SNAKE_CASE_       :				Optional[Any]       				=  """ssube/stable-diffusion-x4-upscaler-onnx"""

				def 							lowercase_					(     self							:    int					,  UpperCamelCase__							:    Union[str, Any]=0)->       Tuple:



						'''simple docstring'''


						__lowerCAmelCase:	int   				=      floats_tensor((1, 3, 1_2_8, 1_2_8)					,  rng=random.Random(UpperCamelCase__))
						__lowerCAmelCase:	str   				=      torch.manual_seed(UpperCamelCase__)
						__lowerCAmelCase:	Optional[Any]   				=      {
						    "prompt": "A painting of a squirrel eating a burger",
						    "image": image,
						    "generator": generator,
						    "num_inference_steps": 3,
						    "guidance_scale": 7.5,
						    "output_type": "numpy",
						}
						return inputs

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



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,  provider="CPUExecutionProvider")
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	Tuple   				=      self.get_dummy_inputs()
						__lowerCAmelCase:	Optional[int]   				=      pipe(**UpperCamelCase__).images
						__lowerCAmelCase:	int   				=      image[0, -3:, -3:, -1].flatten()

						# started as 128, should now be 512
						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Dict   				=      np.array(
						    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223])
						assert np.abs(image_slice - expected_slice).max() < 1e-1

				def 							lowercase_					(     self							:    str)->       Dict:



						'''simple docstring'''


						__lowerCAmelCase:	str   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,  provider="CPUExecutionProvider")
						__lowerCAmelCase:	Union[str, Any]   				=      PNDMScheduler.from_config(pipe.scheduler.config					,  skip_prk_steps=UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	str   				=      self.get_dummy_inputs()
						__lowerCAmelCase:	Tuple   				=      pipe(**UpperCamelCase__).images
						__lowerCAmelCase:	Dict   				=      image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Union[str, Any]   				=      np.array(
						    [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964])
						assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1

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



						'''simple docstring'''


						__lowerCAmelCase:	Any   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,  provider="CPUExecutionProvider")
						__lowerCAmelCase:	List[str]   				=      DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	List[str]   				=      np.array(
						    [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515])

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

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



						'''simple docstring'''


						__lowerCAmelCase:	Dict   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,  provider="CPUExecutionProvider")
						__lowerCAmelCase:	int   				=      EulerDiscreteScheduler.from_config(pipe.scheduler.config)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Optional[int]   				=      np.array(
						    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223])
						assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1




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



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,  provider="CPUExecutionProvider")
						__lowerCAmelCase:	List[Any]   				=      EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Union[str, Any]   				=      np.array(
						    [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043])

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





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

				@property
				def 							lowercase_					(     self							:    Tuple)->       Optional[Any]:



						'''simple docstring'''


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

				@property
				def 							lowercase_					(     self							:    int)->       List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:	Dict   				=      ort.SessionOptions()
						__lowerCAmelCase:	str   				=      False
						return options

				def 							lowercase_					(     self							:    str)->       str:



						'''simple docstring'''


						__lowerCAmelCase:	Tuple   				=      load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/img2img/sketch-mountains-input.jpg")
						__lowerCAmelCase:	List[Any]   				=      init_image.resize((1_2_8, 1_2_8))
						# using the PNDM scheduler by default
						__lowerCAmelCase:	Dict   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(
						    "ssube/stable-diffusion-x4-upscaler-onnx"					,  provider=self.gpu_provider					,  sess_options=self.gpu_options					,  )
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

						__lowerCAmelCase:	Union[str, Any]   				=      torch.manual_seed(0)
						__lowerCAmelCase:	List[Any]   				=      pipe(
						    prompt=UpperCamelCase__					,  image=UpperCamelCase__					,  guidance_scale=7.5					,  num_inference_steps=1_0					,  generator=UpperCamelCase__					,  output_type="np"					,  )
						__lowerCAmelCase:	str   				=      output.images
						__lowerCAmelCase:	Optional[Any]   				=      images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

						assert images.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Dict   				=      np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972])
						# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




				def 							lowercase_					(     self							:    Dict)->       Any:



						'''simple docstring'''


						__lowerCAmelCase:	Optional[int]   				=      load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/img2img/sketch-mountains-input.jpg")
						__lowerCAmelCase:	str   				=      init_image.resize((1_2_8, 1_2_8))
						__lowerCAmelCase:	Union[str, Any]   				=      LMSDiscreteScheduler.from_pretrained(
						    "ssube/stable-diffusion-x4-upscaler-onnx"					,  subfolder="scheduler")
						__lowerCAmelCase:	Dict   				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(
						    "ssube/stable-diffusion-x4-upscaler-onnx"					,  scheduler=UpperCamelCase__					,  provider=self.gpu_provider					,  sess_options=self.gpu_options					,  )
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

						__lowerCAmelCase:	Dict   				=      torch.manual_seed(0)
						__lowerCAmelCase:	Dict   				=      pipe(
						    prompt=UpperCamelCase__					,  image=UpperCamelCase__					,  guidance_scale=7.5					,  num_inference_steps=2_0					,  generator=UpperCamelCase__					,  output_type="np"					,  )
						__lowerCAmelCase:	Optional[int]   				=      output.images
						__lowerCAmelCase:	List[str]   				=      images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

						assert images.shape == (1, 5_1_2, 5_1_2, 3)
						__lowerCAmelCase:	Optional[int]   				=      np.array(
						    [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566])
						# 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"""


from math import ceil






def    a__   (   __SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)     ->     str:
		__lowerCAmelCase:	Tuple   				=      list(range(0 ,			__SCREAMING_SNAKE_CASE			)			)

		__lowerCAmelCase:	Optional[Any]   				=      [item for sublist in list(device_map.values()			) for item in sublist]

		# Duplicate check
		__lowerCAmelCase:	List[Any]   				=      []
		for i in device_map_blocks:
				if device_map_blocks.count(__SCREAMING_SNAKE_CASE			) > 1 and i not in duplicate_blocks:
						duplicate_blocks.append(__SCREAMING_SNAKE_CASE			)
    # Missing blocks
		__lowerCAmelCase:	Optional[Any]   				=      [i for i in blocks if i not in device_map_blocks]
		__lowerCAmelCase:	List[Any]   				=      [i for i in device_map_blocks if i not in blocks]

		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
				    " These attention blocks were specified more than once: " + str(__SCREAMING_SNAKE_CASE			)			)
		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "There are attention blocks for this model that are not specified in the device_map. Add these attention "
				    "blocks to a device on the device_map: " + str(__SCREAMING_SNAKE_CASE			)			)
		if len(__SCREAMING_SNAKE_CASE			) != 0:
				raise ValueError(
				    "The device_map contains more attention blocks than this model has. Remove these from the device_map:"
				    + str(__SCREAMING_SNAKE_CASE			)			)






def    a__   (   __SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)     ->     str:
		__lowerCAmelCase:	List[Any]   				=      list(range(__SCREAMING_SNAKE_CASE			)			)
		__lowerCAmelCase:	Dict   				=      int(ceil(n_layers / len(__SCREAMING_SNAKE_CASE			)			)			)
		__lowerCAmelCase:	Union[str, Any]   				=      [layers[i : i + n_blocks] for i in range(0 ,			__SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)]

		return dict(zip(__SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE			)			)


