






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 	_UpperCAmelCase  (  _A				,							unittest.TestCase		):




      """simple docstring"""



      A          =    '''ssube/stable-diffusion-x4-upscaler-onnx'''
      def 			snake_case_      (   self    ,	_lowerCAmelCase=0		):



          '''simple docstring'''
          lowerCAmelCase__   :Dict      							=				floats_tensor((1, 3, 128, 128)    ,	rng=random.Random(_lowerCAmelCase		)		)
          lowerCAmelCase__   :str      							=				torch.manual_seed(_lowerCAmelCase		)
          lowerCAmelCase__   :Optional[int]      							=				{
              "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 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[Any]      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,	provider="CPUExecutionProvider"		)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

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

          # started as 128, should now be 512
          assert image.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :List[Any]      							=				np.array(
              [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]		)
          assert np.abs(image_slice - expected_slice		).max() < 1e-1
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,	provider="CPUExecutionProvider"		)
          lowerCAmelCase__   :Union[str, Any]      							=				PNDMScheduler.from_config(pipe.scheduler.config    ,	skip_prk_steps=_lowerCAmelCase		)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

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

          assert image.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :Optional[int]      							=				np.array(
              [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964]		)
          assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,	provider="CPUExecutionProvider"		)
          lowerCAmelCase__   :Tuple      							=				DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

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

          assert image.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :int      							=				np.array(
              [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515]		)

          assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :List[Any]      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,	provider="CPUExecutionProvider"		)
          lowerCAmelCase__   :Union[str, Any]      							=				EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

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

          assert image.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :Dict      							=				np.array(
              [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]		)
          assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1



      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Union[str, Any]      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,	provider="CPUExecutionProvider"		)
          lowerCAmelCase__   :List[str]      							=				EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

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

          assert image.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :int      							=				np.array(
              [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043]		)

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







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




      """simple docstring"""



      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[Any]      							=				ort.SessionOptions()
          lowerCAmelCase__   :Dict      							=				False
          return options
      def 			snake_case_      (   self		):



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

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

          lowerCAmelCase__   :List[Any]      							=				torch.manual_seed(0		)
          lowerCAmelCase__   :int      							=				pipe(
              prompt=_lowerCAmelCase    ,	image=_lowerCAmelCase    ,	guidance_scale=7.5    ,	num_inference_steps=10    ,	generator=_lowerCAmelCase    ,	output_type="np"    ,	)
          lowerCAmelCase__   :int      							=				output.images
          lowerCAmelCase__   :List[Any]      							=				images[0, 255:258, 383:386, -1]

          assert images.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :Union[str, Any]      							=				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 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :List[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((128, 128)		)
          lowerCAmelCase__   :Union[str, Any]      							=				LMSDiscreteScheduler.from_pretrained(
              "ssube/stable-diffusion-x4-upscaler-onnx"    ,	subfolder="scheduler"		)
          lowerCAmelCase__   :List[str]      							=				OnnxStableDiffusionUpscalePipeline.from_pretrained(
              "ssube/stable-diffusion-x4-upscaler-onnx"    ,	scheduler=_lowerCAmelCase    ,	provider=self.gpu_provider    ,	sess_options=self.gpu_options    ,	)
          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

          lowerCAmelCase__   :Optional[Any]      							=				"A fantasy landscape, trending on artstation"

          lowerCAmelCase__   :List[str]      							=				torch.manual_seed(0		)
          lowerCAmelCase__   :Optional[Any]      							=				pipe(
              prompt=_lowerCAmelCase    ,	image=_lowerCAmelCase    ,	guidance_scale=7.5    ,	num_inference_steps=20    ,	generator=_lowerCAmelCase    ,	output_type="np"    ,	)
          lowerCAmelCase__   :Any      							=				output.images
          lowerCAmelCase__   :int      							=				images[0, 255:258, 383:386, -1]

          assert images.shape == (1, 512, 512, 3)
          lowerCAmelCase__   :str      							=				np.array(
              [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566]		)
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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











from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a    :   Dict        =			logging.get_logger(__name__)

_a    :   Optional[Any]        =			{
    """caidas/swin2sr-classicalsr-x2-64""": (
        """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json"""
    ),
}







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    '''swin2sr'''

      A          =    {
          '''hidden_size''': '''embed_dim''',
          '''num_attention_heads''': '''num_heads''',
          '''num_hidden_layers''': '''num_layers''',
      }
      def __init__(   self    ,	_lowerCAmelCase=64    ,	_lowerCAmelCase=1    ,	_lowerCAmelCase=3    ,	_lowerCAmelCase=180    ,	_lowerCAmelCase=[6, 6, 6, 6, 6, 6]    ,	_lowerCAmelCase=[6, 6, 6, 6, 6, 6]    ,	_lowerCAmelCase=8    ,	_lowerCAmelCase=2.0    ,	_lowerCAmelCase=True    ,	_lowerCAmelCase=0.0    ,	_lowerCAmelCase=0.0    ,	_lowerCAmelCase=0.1    ,	_lowerCAmelCase="gelu"    ,	_lowerCAmelCase=False    ,	_lowerCAmelCase=0.02    ,	_lowerCAmelCase=1e-5    ,	_lowerCAmelCase=2    ,	_lowerCAmelCase=1.0    ,	_lowerCAmelCase="1conv"    ,	_lowerCAmelCase="pixelshuffle"    ,	**_lowerCAmelCase    ,	):



          '''simple docstring'''
          super().__init__(**_lowerCAmelCase		)

          lowerCAmelCase__   :Union[str, Any]      							=				image_size
          lowerCAmelCase__   :List[Any]      							=				patch_size
          lowerCAmelCase__   :Any      							=				num_channels
          lowerCAmelCase__   :Union[str, Any]      							=				embed_dim
          lowerCAmelCase__   :Optional[int]      							=				depths
          lowerCAmelCase__   :int      							=				len(_lowerCAmelCase		)
          lowerCAmelCase__   :List[str]      							=				num_heads
          lowerCAmelCase__   :str      							=				window_size
          lowerCAmelCase__   :List[str]      							=				mlp_ratio
          lowerCAmelCase__   :List[Any]      							=				qkv_bias
          lowerCAmelCase__   :Union[str, Any]      							=				hidden_dropout_prob
          lowerCAmelCase__   :Optional[int]      							=				attention_probs_dropout_prob
          lowerCAmelCase__   :Dict      							=				drop_path_rate
          lowerCAmelCase__   :Tuple      							=				hidden_act
          lowerCAmelCase__   :Dict      							=				use_absolute_embeddings
          lowerCAmelCase__   :Tuple      							=				layer_norm_eps
          lowerCAmelCase__   :Dict      							=				initializer_range
          lowerCAmelCase__   :Optional[int]      							=				upscale
          lowerCAmelCase__   :Optional[Any]      							=				img_range
          lowerCAmelCase__   :List[str]      							=				resi_connection
          lowerCAmelCase__   :Union[str, Any]      							=				upsampler



