


"""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 				SCREAMING_SNAKE_CASE__    (		lowercase       ,   unittest.TestCase    ):
       """simple docstring"""


       a  :    Union[str, Any]       ="ssube/stable-diffusion-x4-upscaler-onnx"

       def 	lowercase__							(						self		,					snake_case__=0						):






         """simple docstring"""





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






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,					provider="CPUExecutionProvider"						)
         pipe.set_progress_bar_config(disable=snake_case__						)

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

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






         """simple docstring"""





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

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

         assert image.shape == (1, 512, 512, 3)
         lowerCAmelCase					:					List[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						):






         """simple docstring"""





         lowerCAmelCase					:					Union[str, Any]								=							OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,					provider="CPUExecutionProvider"						)
         lowerCAmelCase					:					Optional[Any]								=							DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
         pipe.set_progress_bar_config(disable=snake_case__						)

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

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






         """simple docstring"""





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

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

         assert image.shape == (1, 512, 512, 3)
         lowerCAmelCase					:					str								=							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						):






         """simple docstring"""





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

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

         assert image.shape == (1, 512, 512, 3)
         lowerCAmelCase					:					str								=							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 				SCREAMING_SNAKE_CASE__    (		unittest.TestCase    ):
       """simple docstring"""


       @property
       def 	lowercase__							(						self						):






         """simple docstring"""





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

       @property
       def 	lowercase__							(						self						):






         """simple docstring"""





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

       def 	lowercase__							(						self						):






         """simple docstring"""





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

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

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

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






         """simple docstring"""





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

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

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

         assert images.shape == (1, 512, 512, 3)
         lowerCAmelCase					:					List[Any]								=							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 typing import List, Optional

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


lowerCAmelCase__				    =       logging.get_logger(__name__)

lowerCAmelCase__				    =       {
    '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       a  :    Dict       ="autoformer"
       a  :    Dict       ={
           "hidden_size": "d_model",
           "num_attention_heads": "encoder_attention_heads",
           "num_hidden_layers": "encoder_layers",
       }

       def __init__(						self		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = "student_t"		,					snake_case__ = "nll"		,					snake_case__ = 1		,					snake_case__ = [1, 2, 3, 4, 5, 6, 7]		,					snake_case__ = True		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = 64		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 32		,					snake_case__ = 32		,					snake_case__ = "gelu"		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 100		,					snake_case__ = 0.02		,					snake_case__ = True		,					snake_case__=True		,					snake_case__ = 10		,					snake_case__ = 25		,					snake_case__ = 3		,					**snake_case__		,					):






         """simple docstring"""





         lowerCAmelCase					:					Any								=							prediction_length
         lowerCAmelCase					:					Dict								=							context_length if context_length is not None else prediction_length
         lowerCAmelCase					:					Tuple								=							distribution_output
         lowerCAmelCase					:					List[Any]								=							loss
         lowerCAmelCase					:					int								=							input_size
         lowerCAmelCase					:					str								=							num_time_features
         lowerCAmelCase					:					str								=							lags_sequence
         lowerCAmelCase					:					List[str]								=							scaling
         lowerCAmelCase					:					List[Any]								=							num_dynamic_real_features
         lowerCAmelCase					:					Tuple								=							num_static_real_features
         lowerCAmelCase					:					Dict								=							num_static_categorical_features
         if cardinality is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The cardinality should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Any								=							cardinality
         else:
           lowerCAmelCase					:					Union[str, Any]								=							[0]
         if embedding_dimension is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The embedding dimension should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Tuple								=							embedding_dimension
         else:
           lowerCAmelCase					:					Any								=							[min(50		,					(cat + 1) // 2						) for cat in self.cardinality]
         lowerCAmelCase					:					Any								=							num_parallel_samples

         # Transformer architecture configuration
         lowerCAmelCase					:					str								=							input_size * len(self.lags_sequence						) + self._number_of_features
         lowerCAmelCase					:					Any								=							d_model
         lowerCAmelCase					:					List[str]								=							encoder_attention_heads
         lowerCAmelCase					:					Union[str, Any]								=							decoder_attention_heads
         lowerCAmelCase					:					Optional[int]								=							encoder_ffn_dim
         lowerCAmelCase					:					Optional[Any]								=							decoder_ffn_dim
         lowerCAmelCase					:					int								=							encoder_layers
         lowerCAmelCase					:					int								=							decoder_layers

         lowerCAmelCase					:					List[Any]								=							dropout
         lowerCAmelCase					:					Optional[int]								=							attention_dropout
         lowerCAmelCase					:					Union[str, Any]								=							activation_dropout
         lowerCAmelCase					:					Optional[int]								=							encoder_layerdrop
         lowerCAmelCase					:					Dict								=							decoder_layerdrop

         lowerCAmelCase					:					Tuple								=							activation_function
         lowerCAmelCase					:					Optional[Any]								=							init_std

         lowerCAmelCase					:					List[Any]								=							use_cache

         # Autoformer
         lowerCAmelCase					:					Any								=							label_length
         lowerCAmelCase					:					Any								=							moving_average
         lowerCAmelCase					:					Optional[Any]								=							autocorrelation_factor

         super().__init__(is_encoder_decoder=snake_case__		,					**snake_case__						)







       @property
       def 	lowercase__							(						self						):






         """simple docstring"""





         return (
             sum(self.embedding_dimension						)
             + self.num_dynamic_real_features
             + self.num_time_features
             + self.num_static_real_features
             + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
         )





