'''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 				_lowercase	(      lowerCAmelCase		,unittest.TestCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Optional[Any]      							=   '''ssube/stable-diffusion-x4-upscaler-onnx'''




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_=0							)			->			Optional[int]:



         '''simple docstring'''



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



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

         UpperCAmelCase__							:				Dict   				=  self.get_dummy_inputs()
         UpperCAmelCase__							:				List[str]   				=  pipe(**lowerCamelCase_							).images
         UpperCAmelCase__							:				List[Any]   				=  image[0, -3:, -3:, -1].flatten()

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




      def 		lowerCAmelCase__					(				self							)			->			Dict:



         '''simple docstring'''



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

         UpperCAmelCase__							:				Tuple   				=  self.get_dummy_inputs()
         UpperCAmelCase__							:				Dict   				=  pipe(**lowerCamelCase_							).images
         UpperCAmelCase__							:				List[Any]   				=  image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         UpperCAmelCase__							:				Dict   				=  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 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



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

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

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



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				Optional[Any]   				=  EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

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

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



         '''simple docstring'''



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

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

         assert image.shape == (1, 512, 512, 3)
         UpperCAmelCase__							:				Tuple   				=  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 				_lowercase	(      unittest.TestCase   ):
      '''simple docstring'''


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



         '''simple docstring'''



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




      @property
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				Tuple   				=  ort.SessionOptions()
         UpperCAmelCase__							:				Optional[int]   				=  False
         return options




      def 		lowerCAmelCase__					(				self							)			->			Optional[Any]:



         '''simple docstring'''



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

         UpperCAmelCase__							:				Tuple   				=  '''A fantasy landscape, trending on artstation'''

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

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



         '''simple docstring'''



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

         UpperCAmelCase__							:				str   				=  '''A fantasy landscape, trending on artstation'''

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

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





'''simple docstring'''

from typing import List, Optional, Union

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


UpperCamelCase__     :	List[Any]				=			logging.get_logger(__name__)

UpperCamelCase__     :	Optional[Any]				=			{
    'huggingface/time-series-transformer-tourism-monthly': (
        'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}


class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Any      							=   '''time_series_transformer'''
      UpperCAmelCase_      :      List[Any]      							=   {
          '''hidden_size''': '''d_model''',
          '''num_attention_heads''': '''encoder_attention_heads''',
          '''num_hidden_layers''': '''encoder_layers''',
      }




      def __init__(				self					,lowerCamelCase_ = None					,lowerCamelCase_ = None					,lowerCamelCase_ = "student_t"					,lowerCamelCase_ = "nll"					,lowerCamelCase_ = 1					,lowerCamelCase_ = [1, 2, 3, 4, 5, 6, 7]					,lowerCamelCase_ = "mean"					,lowerCamelCase_ = 0					,lowerCamelCase_ = 0					,lowerCamelCase_ = 0					,lowerCamelCase_ = 0					,lowerCamelCase_ = None					,lowerCamelCase_ = None					,lowerCamelCase_ = 32					,lowerCamelCase_ = 32					,lowerCamelCase_ = 2					,lowerCamelCase_ = 2					,lowerCamelCase_ = 2					,lowerCamelCase_ = 2					,lowerCamelCase_ = True					,lowerCamelCase_ = "gelu"					,lowerCamelCase_ = 64					,lowerCamelCase_ = 0.1					,lowerCamelCase_ = 0.1					,lowerCamelCase_ = 0.1					,lowerCamelCase_ = 0.1					,lowerCamelCase_ = 0.1					,lowerCamelCase_ = 100					,lowerCamelCase_ = 0.02					,lowerCamelCase_=True					,**lowerCamelCase_					,)			->			Tuple:



         '''simple docstring'''



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

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

         UpperCAmelCase__							:				Optional[Any]   				=  dropout
         UpperCAmelCase__							:				Any   				=  attention_dropout
         UpperCAmelCase__							:				Optional[int]   				=  activation_dropout
         UpperCAmelCase__							:				List[Any]   				=  encoder_layerdrop
         UpperCAmelCase__							:				Optional[int]   				=  decoder_layerdrop

         UpperCAmelCase__							:				List[Any]   				=  activation_function
         UpperCAmelCase__							:				List[Any]   				=  init_std

         UpperCAmelCase__							:				Optional[Any]   				=  use_cache

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




      @property
      def 		lowerCAmelCase__					(				self							)			->			int:



         '''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
         )




