





from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
      import torch

if is_torch_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm


SCREAMING_SNAKE_CASE_		     = logging.get_logger(__name__)

@dataclass
class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     __snake_case					:			List[str]				=    [
         "no_inference",
         "no_cuda",
         "no_tpu",
         "no_speed",
         "no_memory",
         "no_env_print",
         "no_multi_process",
     ]






     def __init__(							self		:					Dict		,**lowerCamelCase__		:					Any )  ->	Any:




           '''simple docstring'''


           for deprecated_arg in self.deprecated_args:
                 if deprecated_arg in kwargs:
                       SCREAMING_SNAKE_CASE	=		deprecated_arg[3:]
                       setattr(self		,lowerCamelCase__		,not kwargs.pop(lowerCamelCase__ ) )
                       logger.warning(
                           F"""{deprecated_arg} is depreciated. Please use --no_{positive_arg} or"""
                           F""" {positive_arg}={kwargs[positive_arg]}""" )

           SCREAMING_SNAKE_CASE	=		kwargs.pop("""torchscript"""		,self.torchscript )
           SCREAMING_SNAKE_CASE	=		kwargs.pop("""torch_xla_tpu_print_metrics"""		,self.torch_xla_tpu_print_metrics )
           SCREAMING_SNAKE_CASE	=		kwargs.pop("""fp16_opt_level"""		,self.fpaa_opt_level )
           super().__init__(**lowerCamelCase__ )

     __snake_case					:			bool				=    field(default=lowerCAmelCase_							,   metadata={"help": "Trace the models using torchscript"}     )
     __snake_case					:			bool				=    field(default=lowerCAmelCase_							,   metadata={"help": "Print Xla/PyTorch tpu metrics"}     )
     __snake_case					:			str				=    field(
         default="O1"							,   metadata={
             "help": (
                 "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
                 "See details at https://nvidia.github.io/apex/amp.html"
             )
         }							,   )






     @cached_property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Tuple["torch.device", int]:




           '''simple docstring'''


           requires_backends(self		,["""torch"""] )
           logger.info("""PyTorch: setting up devices""" )
           if not self.cuda:
                 SCREAMING_SNAKE_CASE	=		torch.device("""cpu""" )
                 SCREAMING_SNAKE_CASE	=		0
           elif is_torch_tpu_available():
                 SCREAMING_SNAKE_CASE	=		xm.xla_device()
                 SCREAMING_SNAKE_CASE	=		0
           else:
                 SCREAMING_SNAKE_CASE	=		torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
                 SCREAMING_SNAKE_CASE	=		torch.cuda.device_count()
           return device, n_gpu






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




           '''simple docstring'''


           return is_torch_tpu_available() and self.tpu






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	int:




           '''simple docstring'''


           requires_backends(self		,["""torch"""] )
           # TODO(PVP): currently only single GPU is supported
           return torch.cuda.current_device()






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	"torch.device":




           '''simple docstring'''


           requires_backends(self		,["""torch"""] )
           return self._setup_devices[0]






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Dict:




           '''simple docstring'''


           requires_backends(self		,["""torch"""] )
           return self._setup_devices[1]






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any] )  ->	str:




           '''simple docstring'''


           return self.n_gpu > 0









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__				(   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					List[str]=0 )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		floats_tensor((1, 3, 128, 128)		,rng=random.Random(lowerCamelCase__ ) )
           SCREAMING_SNAKE_CASE	=		torch.manual_seed(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		{
               """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        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,provider="""CPUExecutionProvider""" )
           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.get_dummy_inputs()
           SCREAMING_SNAKE_CASE	=		pipe(**lowerCamelCase__ ).images
           SCREAMING_SNAKE_CASE	=		image[0, -3:, -3:, -1].flatten()

           # started as 128, should now be 512
           assert image.shape == (1, 512, 512, 3)
           SCREAMING_SNAKE_CASE	=		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        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,provider="""CPUExecutionProvider""" )
           SCREAMING_SNAKE_CASE	=		PNDMScheduler.from_config(pipe.scheduler.config		,skip_prk_steps=lowerCamelCase__ )
           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.get_dummy_inputs()
           SCREAMING_SNAKE_CASE	=		pipe(**lowerCamelCase__ ).images
           SCREAMING_SNAKE_CASE	=		image[0, -3:, -3:, -1]

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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,provider="""CPUExecutionProvider""" )
           SCREAMING_SNAKE_CASE	=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.get_dummy_inputs()
           SCREAMING_SNAKE_CASE	=		pipe(**lowerCamelCase__ ).images
           SCREAMING_SNAKE_CASE	=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 512, 512, 3)
           SCREAMING_SNAKE_CASE	=		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        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,provider="""CPUExecutionProvider""" )
           SCREAMING_SNAKE_CASE	=		EulerDiscreteScheduler.from_config(pipe.scheduler.config )
           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.get_dummy_inputs()
           SCREAMING_SNAKE_CASE	=		pipe(**lowerCamelCase__ ).images
           SCREAMING_SNAKE_CASE	=		image[0, -3:, -3:, -1]

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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,provider="""CPUExecutionProvider""" )
           SCREAMING_SNAKE_CASE	=		EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.get_dummy_inputs()
           SCREAMING_SNAKE_CASE	=		pipe(**lowerCamelCase__ ).images
           SCREAMING_SNAKE_CASE	=		image[0, -3:, -3:, -1]

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



     '''simple docstring'''

     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Optional[int]:




           '''simple docstring'''


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






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any] )  ->	List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		ort.SessionOptions()
           SCREAMING_SNAKE_CASE	=		False
           return options






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Tuple:




           '''simple docstring'''


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

           SCREAMING_SNAKE_CASE	=		"""A fantasy landscape, trending on artstation"""

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

           assert images.shape == (1, 512, 512, 3)
           SCREAMING_SNAKE_CASE	=		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        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Dict:




           '''simple docstring'''


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

           SCREAMING_SNAKE_CASE	=		"""A fantasy landscape, trending on artstation"""

           SCREAMING_SNAKE_CASE	=		torch.manual_seed(0 )
           SCREAMING_SNAKE_CASE	=		pipe(
               prompt=lowerCamelCase__		,image=lowerCamelCase__		,guidance_scale=7.5		,num_inference_steps=20		,generator=lowerCamelCase__		,output_type="""np"""		,)
           SCREAMING_SNAKE_CASE	=		output.images
           SCREAMING_SNAKE_CASE	=		images[0, 255:258, 383:386, -1]

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


