



import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
 from ... import PreTrainedTokenizerBase, TensorType

a_   :int        =      logging.get_logger(__name__)




class 					snake_case__						(       snake_case_     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	'''vision-encoder-decoder'''
     _SCREAMING_SNAKE_CASE						=	True






     def __init__(       self  :  Tuple, **_snake_case  :  Dict					)   ->List[str]:
            super().__init__(**UpperCamelCase__					)
            if "encoder" not in kwargs or "decoder" not in kwargs:
                   raise ValueError(
                       F'''A configuraton of type {self.model_type} cannot be instantiated because '''
                       F'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}'''					)

            snake_case__							:	Any   	=	kwargs.pop('encoder'					)
            snake_case__							:	Optional[Any]   	=	encoder_config.pop('model_type'					)
            snake_case__							:	Optional[int]   	=	kwargs.pop('decoder'					)
            snake_case__							:	Any   	=	decoder_config.pop('model_type'					)

            snake_case__							:	Any   	=	AutoConfig.for_model(UpperCamelCase__, **UpperCamelCase__					)
            snake_case__							:	Optional[Any]   	=	AutoConfig.for_model(UpperCamelCase__, **UpperCamelCase__					)
            snake_case__							:	Dict   	=	True






     @classmethod
     def    lowercase_   (       cls  :  Optional[Any], _snake_case  :  str, _snake_case  :  Optional[int], **_snake_case  :  Optional[int]					)   ->PretrainedConfig:
            logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'					)
            snake_case__							:	Optional[int]   	=	True
            snake_case__							:	int   	=	True

            return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **UpperCamelCase__					)






     def    lowercase_   (       self  :  List[Any]					)   ->Optional[Any]:
            snake_case__							:	Any   	=	copy.deepcopy(self.__dict__					)
            snake_case__							:	Union[str, Any]   	=	self.encoder.to_dict()
            snake_case__							:	List[Any]   	=	self.decoder.to_dict()
            snake_case__							:	Any   	=	self.__class__.model_type
            return output




class 					snake_case__						(       snake_case_     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	version.parse("""1.11"""     )






     @property
     def    lowercase_   (       self  :  str					)   ->Mapping[str, Mapping[int, str]]:
            return OrderedDict(
                [
                    ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
                ]					)






     @property
     def    lowercase_   (       self  :  Optional[Any]					)   ->float:
            return 1e-4






     @property
     def    lowercase_   (       self  :  Optional[int]					)   ->Mapping[str, Mapping[int, str]]:
            return OrderedDict({'last_hidden_state': {0: 'batch', 1: 'encoder_sequence'}}					)




class 					snake_case__						(       snake_case_     ):






     """simple docstring"""


     @property
     def    lowercase_   (       self  :  List[Any]					)   ->Mapping[str, Mapping[int, str]]:
            snake_case__							:	Tuple   	=	OrderedDict()
            snake_case__							:	Tuple   	=	{0: "batch", 1: "past_decoder_sequence + sequence"}
            snake_case__							:	Optional[int]   	=	{0: "batch", 1: "past_decoder_sequence + sequence"}
            snake_case__							:	Optional[Any]   	=	{0: "batch", 1: "encoder_sequence"}

            return common_inputs






     def    lowercase_   (       self  :  Optional[int], _snake_case  :  List[str], _snake_case  :  List[Any] = -1, _snake_case  :  Tuple = -1, _snake_case  :  int = False, _snake_case  :  List[Any] = None, )   ->Mapping[str, Any]:
            import torch

            snake_case__							:	Optional[Any]   	=	OrderedDict()

            snake_case__							:	Optional[Any]   	=	super().generate_dummy_inputs(
                UpperCamelCase__, batch_size=UpperCamelCase__, seq_length=UpperCamelCase__, is_pair=UpperCamelCase__, framework=UpperCamelCase__					)

            snake_case__							:	Optional[int]   	=	dummy_input["input_ids"].shape
            snake_case__							:	Tuple   	=	(batch, encoder_sequence, self._config.encoder_hidden_size)
            snake_case__							:	Tuple   	=	dummy_input.pop('input_ids'					)
            snake_case__							:	Tuple   	=	dummy_input.pop('attention_mask'					)
            snake_case__							:	Union[str, Any]   	=	torch.zeros(UpperCamelCase__					)

            return common_inputs




class 					snake_case__						(       snake_case_     ):






     """simple docstring"""


     @property
     def    lowercase_   (       self  :  Dict					)   ->None:
            pass






     def    lowercase_   (       self  :  str, _snake_case  :  Optional[Any]					)   ->OnnxConfig:
            return VisionEncoderDecoderEncoderOnnxConfig(UpperCamelCase__					)






     def    lowercase_   (       self  :  Tuple, _snake_case  :  Optional[int], _snake_case  :  Union[str, Any], _snake_case  :  Any = "default"					)   ->OnnxConfig:
            snake_case__							:	str   	=	encoder_config.hidden_size
            return VisionEncoderDecoderDecoderOnnxConfig(UpperCamelCase__, UpperCamelCase__					)










"""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 _lowerCAmelCase				(      snake_case_    ,							unittest.TestCase	):
   # TODO: is there an appropriate internal test set?
   __UpperCAmelCase :       Optional[Any]							  =  '''ssube/stable-diffusion-x4-upscaler-onnx'''







   def  lowerCamelCase		(	self						,	UpperCamelCase__=0						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    floats_tensor((1, 3, 128, 128)						,	rng=random.Random(UpperCamelCase__						)						)
       snake_case    :      Any      					=    torch.manual_seed(UpperCamelCase__						)
       snake_case    :      List[str]      					=    {
           "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  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

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

       # started as 128, should now be 512
       assert image.shape == (1, 512, 512, 3)
       snake_case    :      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 - expected_slice						).max() < 1e-1







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

       '''simple docstring'''




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

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

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Dict      					=    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  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




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

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

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

       '''simple docstring'''




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

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

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

       '''simple docstring'''




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

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

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      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 _lowerCAmelCase				(      unittest.TestCase	):







   @property
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




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







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

       '''simple docstring'''




       snake_case    :      List[Any]      					=    ort.SessionOptions()
       snake_case    :      str      					=    False
       return options







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      str      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Tuple      					=    init_image.resize((128, 128)						)
       # using the PNDM scheduler by default
       snake_case    :      Tuple      					=    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__						)

       snake_case    :      List[Any]      					=    "A fantasy landscape, trending on artstation"

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

       assert images.shape == (1, 512, 512, 3)
       snake_case    :      int      					=    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  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Optional[Any]      					=    init_image.resize((128, 128)						)
       snake_case    :      Union[str, Any]      					=    LMSDiscreteScheduler.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	subfolder="scheduler"						)
       snake_case    :      List[Any]      					=    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__						)

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

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

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





