


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 					__magic_name__		(   lowercase__    , unittest.TestCase):
     A:						Any								=					'ssube/stable-diffusion-x4-upscaler-onnx'


     def    UpperCAmelCase__		(					self							:   Optional[int]							,		lowerCamelCase__							:   Any=0	)     ->					Any:





      '''simple docstring'''






      UpperCamelCase__    :			Optional[Any]      				=      floats_tensor((1, 3, 128, 128)							,		rng=random.Random(__lowercase	)	)
      UpperCamelCase__    :			List[Any]      				=      torch.manual_seed(__lowercase	)
      UpperCamelCase__    :			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    UpperCAmelCase__		(					self							:   Any	)     ->					List[Any]:





      '''simple docstring'''






      UpperCamelCase__    :			Optional[int]      				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='''CPUExecutionProvider'''	)
      pipe.set_progress_bar_config(disable=__lowercase	)

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

      # started as 128, should now be 512
      assert image.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			Union[str, 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    UpperCAmelCase__		(					self							:   Any	)     ->					Dict:





      '''simple docstring'''






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

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

      assert image.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			List[str]      				=      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    UpperCAmelCase__		(					self							:   List[str]	)     ->					Dict:





      '''simple docstring'''






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

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

      assert image.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			Dict      				=      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    UpperCAmelCase__		(					self							:   Optional[Any]	)     ->					Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__    :			Any      				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='''CPUExecutionProvider'''	)
      UpperCamelCase__    :			Dict      				=      EulerDiscreteScheduler.from_config(pipe.scheduler.config	)
      pipe.set_progress_bar_config(disable=__lowercase	)

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

      assert image.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			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.flatten() - expected_slice	).max() < 1E-1


     def    UpperCAmelCase__		(					self							:   Tuple	)     ->					str:





      '''simple docstring'''






      UpperCamelCase__    :			Dict      				=      OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='''CPUExecutionProvider'''	)
      UpperCamelCase__    :			Optional[int]      				=      EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config	)
      pipe.set_progress_bar_config(disable=__lowercase	)

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

      assert image.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			List[Any]      				=      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 					__magic_name__		(   unittest.TestCase):


     @property
     def    UpperCAmelCase__		(					self							:   Dict	)     ->					Optional[Any]:





      '''simple docstring'''






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


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





      '''simple docstring'''






      UpperCamelCase__    :			str      				=      ort.SessionOptions()
      UpperCamelCase__    :			Optional[Any]      				=      False
      return options


     def    UpperCAmelCase__		(					self							:   List[Any]	)     ->					int:





      '''simple docstring'''






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

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

      UpperCamelCase__    :			Tuple      				=      torch.manual_seed(0	)
      UpperCamelCase__    :			List[str]      				=      pipe(
          prompt=__lowercase							,		image=__lowercase							,		guidance_scale=7.5							,		num_inference_steps=10							,		generator=__lowercase							,		output_type='''np'''							,		)
      UpperCamelCase__    :			str      				=      output.images
      UpperCamelCase__    :			List[str]      				=      images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			List[str]      				=      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    UpperCAmelCase__		(					self							:   str	)     ->					str:





      '''simple docstring'''






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

      UpperCamelCase__    :			Dict      				=      """A fantasy landscape, trending on artstation"""

      UpperCamelCase__    :			Dict      				=      torch.manual_seed(0	)
      UpperCamelCase__    :			Any      				=      pipe(
          prompt=__lowercase							,		image=__lowercase							,		guidance_scale=7.5							,		num_inference_steps=20							,		generator=__lowercase							,		output_type='''np'''							,		)
      UpperCamelCase__    :			Union[str, Any]      				=      output.images
      UpperCamelCase__    :			Union[str, Any]      				=      images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 512, 3)
      UpperCamelCase__    :			int      				=      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










import warnings

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


a		:       Tuple			     = logging.get_logger(__name__)

a		:       Optional[Any]			     = {
    "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json",
}
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : str							       =	'mvp'
      a  : Optional[Any]							       =	['past_key_values']
      a  : int							       =	{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
      def __init__(      self					:			Dict		,      __lowercase					:			Tuple=50267		,      __lowercase					:			Optional[int]=1024		,      __lowercase					:			Any=12		,      __lowercase					:			List[Any]=4096		,      __lowercase					:			Optional[Any]=16		,      __lowercase					:			List[str]=12		,      __lowercase					:			Optional[Any]=4096		,      __lowercase					:			Tuple=16		,      __lowercase					:			Union[str, Any]=0.0		,      __lowercase					:			str=0.0		,      __lowercase					:			Any="gelu"		,      __lowercase					:			Any=1024		,      __lowercase					:			List[str]=0.1		,      __lowercase					:			List[Any]=0.0		,      __lowercase					:			int=0.0		,      __lowercase					:			str=0.02		,      __lowercase					:			Tuple=0.0		,      __lowercase					:			Union[str, Any]=False		,      __lowercase					:			Dict=True		,      __lowercase					:			List[Any]=1		,      __lowercase					:			Optional[Any]=0		,      __lowercase					:			Union[str, Any]=2		,      __lowercase					:			Optional[int]=True		,      __lowercase					:			Dict=2		,      __lowercase					:			int=2		,      __lowercase					:			Union[str, Any]=False		,      __lowercase					:			Union[str, Any]=100		,      __lowercase					:			str=800		,      **__lowercase					:			Union[str, Any]		,      )							->      Any:
        __UpperCAmelCase							:	List[str]           =  vocab_size
        __UpperCAmelCase							:	Union[str, Any]           =  max_position_embeddings
        __UpperCAmelCase							:	Optional[Any]           =  d_model
        __UpperCAmelCase							:	int           =  encoder_ffn_dim
        __UpperCAmelCase							:	Tuple           =  encoder_layers
        __UpperCAmelCase							:	List[str]           =  encoder_attention_heads
        __UpperCAmelCase							:	Any           =  decoder_ffn_dim
        __UpperCAmelCase							:	List[Any]           =  decoder_layers
        __UpperCAmelCase							:	str           =  decoder_attention_heads
        __UpperCAmelCase							:	Optional[int]           =  dropout
        __UpperCAmelCase							:	Tuple           =  attention_dropout
        __UpperCAmelCase							:	int           =  activation_dropout
        __UpperCAmelCase							:	List[Any]           =  activation_function
        __UpperCAmelCase							:	Tuple           =  init_std
        __UpperCAmelCase							:	Any           =  encoder_layerdrop
        __UpperCAmelCase							:	Union[str, Any]           =  decoder_layerdrop
        __UpperCAmelCase							:	List[Any]           =  classifier_dropout
        __UpperCAmelCase							:	Optional[int]           =  use_cache
        __UpperCAmelCase							:	int           =  encoder_layers
        __UpperCAmelCase							:	Union[str, Any]           =  scale_embedding  # scale factor will be sqrt(d_model) if True
        __UpperCAmelCase							:	Tuple           =  use_prompt
        __UpperCAmelCase							:	str           =  prompt_length
        __UpperCAmelCase							:	Union[str, Any]           =  prompt_mid_dim

        super().__init__(
            pad_token_id=__lowercase		,      bos_token_id=__lowercase		,      eos_token_id=__lowercase		,      is_encoder_decoder=__lowercase		,      decoder_start_token_id=__lowercase		,      forced_eos_token_id=__lowercase		,      **__lowercase		,      )

        if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""		,      __lowercase					):
          __UpperCAmelCase							:	Optional[Any]           =  self.bos_token_id
          warnings.warn(
              f"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """
              """The config can simply be saved and uploaded again to be fixed."""					)


