




'''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 					_a (a__,		unittest.TestCase	):





     '''simple docstring'''



     lowerCAmelCase_  :     Tuple          =					"""ssube/stable-diffusion-x4-upscaler-onnx"""







     def 			snake_case_      (				self							,__a=0							)      ->				Dict:
          snake_case			:      Union[str, Any]        =			floats_tensor((1, 3, 128, 128)							,rng=random.Random(__a							)							)
          snake_case			:      Tuple        =			torch.manual_seed(__a							)
          snake_case			:      Dict        =			{
              """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 			snake_case_      (				self							)      ->				List[Any]:
          snake_case			:      Dict        =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,provider="""CPUExecutionProvider"""							)
          pipe.set_progress_bar_config(disable=__a							)

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

          # started as 128, should now be 512
          assert image.shape == (1, 512, 512, 3)
          snake_case			:      Dict        =			np.array(
              [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]							)
          assert np.abs(image_slice - expected_slice							).max() < 1E-1







     def 			snake_case_      (				self							)      ->				Any:
          snake_case			:      Union[str, Any]        =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,provider="""CPUExecutionProvider"""							)
          snake_case			:      List[Any]        =			PNDMScheduler.from_config(pipe.scheduler.config							,skip_prk_steps=__a							)
          pipe.set_progress_bar_config(disable=__a							)

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

          assert image.shape == (1, 512, 512, 3)
          snake_case			:      int        =			np.array(
              [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964]							)
          assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1







     def 			snake_case_      (				self							)      ->				Optional[Any]:
          snake_case			:      List[Any]        =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,provider="""CPUExecutionProvider"""							)
          snake_case			:      str        =			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config							)
          pipe.set_progress_bar_config(disable=__a							)

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

          assert image.shape == (1, 512, 512, 3)
          snake_case			:      List[str]        =			np.array(
              [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515]							)

          assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1







     def 			snake_case_      (				self							)      ->				Any:
          snake_case			:      List[str]        =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,provider="""CPUExecutionProvider"""							)
          snake_case			:      Optional[Any]        =			EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
          pipe.set_progress_bar_config(disable=__a							)

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

          assert image.shape == (1, 512, 512, 3)
          snake_case			:      Optional[Any]        =			np.array(
              [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]							)
          assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1







     def 			snake_case_      (				self							)      ->				Tuple:
          snake_case			:      List[Any]        =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,provider="""CPUExecutionProvider"""							)
          snake_case			:      List[Any]        =			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config							)
          pipe.set_progress_bar_config(disable=__a							)

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

          assert image.shape == (1, 512, 512, 3)
          snake_case			:      Optional[Any]        =			np.array(
              [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043]							)

          assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1







@nightly
@require_onnxruntime
@require_torch_gpu
class 					_a (unittest.TestCase	):





     '''simple docstring'''



     @property
     def 			snake_case_      (				self							)      ->				str:
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )







     @property
     def 			snake_case_      (				self							)      ->				Tuple:
          snake_case			:      Optional[int]        =			ort.SessionOptions()
          snake_case			:      Dict        =			False
          return options







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

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

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

          assert images.shape == (1, 512, 512, 3)
          snake_case			:      List[str]        =			np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972]							)
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

          assert np.abs(image_slice.flatten() - expected_slice							).max() < 2E-2







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

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

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

          assert images.shape == (1, 512, 512, 3)
          snake_case			:      List[Any]        =			np.array(
              [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566]							)
          # 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'''







import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowercase      :   Tuple      =       logging.get_logger(__name__)

lowercase      :   Dict      =       {
    """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""",
}







class 					_a (a__	):





     '''simple docstring'''



     lowerCAmelCase_  :     str          =					"""deta"""
     lowerCAmelCase_  :     Any          =					{
         """hidden_size""": """d_model""",
         """num_attention_heads""": """encoder_attention_heads""",
     }







     def __init__(				self							,__a=None							,__a=900							,__a=2_048							,__a=6							,__a=2_048							,__a=8							,__a=6							,__a=1_024							,__a=8							,__a=0.0							,__a=True							,__a="relu"							,__a=256							,__a=0.1							,__a=0.0							,__a=0.0							,__a=0.02							,__a=1.0							,__a=True							,__a=False							,__a="sine"							,__a=5							,__a=4							,__a=4							,__a=True							,__a=300							,__a=True							,__a=True							,__a=1							,__a=5							,__a=2							,__a=1							,__a=1							,__a=5							,__a=2							,__a=0.1							,__a=0.25							,**__a							,)      ->				int:
          if backbone_config is None:
               logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""							)
               snake_case			:      int        =			CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""]							)
          else:
               if isinstance(__a							,__a							):
                    snake_case			:      str        =			backbone_config.pop("""model_type"""							)
                    snake_case			:      Optional[Any]        =			CONFIG_MAPPING[backbone_model_type]
                    snake_case			:      List[Any]        =			config_class.from_dict(__a							)

          snake_case			:      Any        =			backbone_config
          snake_case			:      Optional[Any]        =			num_queries
          snake_case			:      Dict        =			max_position_embeddings
          snake_case			:      int        =			d_model
          snake_case			:      str        =			encoder_ffn_dim
          snake_case			:      Dict        =			encoder_layers
          snake_case			:      List[Any]        =			encoder_attention_heads
          snake_case			:      int        =			decoder_ffn_dim
          snake_case			:      List[Any]        =			decoder_layers
          snake_case			:      Dict        =			decoder_attention_heads
          snake_case			:      Dict        =			dropout
          snake_case			:      Dict        =			attention_dropout
          snake_case			:      List[Any]        =			activation_dropout
          snake_case			:      Dict        =			activation_function
          snake_case			:      List[Any]        =			init_std
          snake_case			:      Any        =			init_xavier_std
          snake_case			:      List[Any]        =			encoder_layerdrop
          snake_case			:      Optional[Any]        =			auxiliary_loss
          snake_case			:      Optional[int]        =			position_embedding_type
          # deformable attributes
          snake_case			:      Tuple        =			num_feature_levels
          snake_case			:      List[Any]        =			encoder_n_points
          snake_case			:      Dict        =			decoder_n_points
          snake_case			:      int        =			two_stage
          snake_case			:      Any        =			two_stage_num_proposals
          snake_case			:      List[str]        =			with_box_refine
          snake_case			:      Tuple        =			assign_first_stage
          if two_stage is True and with_box_refine is False:
               raise ValueError("""If two_stage is True, with_box_refine must be True."""							)
          # Hungarian matcher
          snake_case			:      Optional[int]        =			class_cost
          snake_case			:      int        =			bbox_cost
          snake_case			:      Optional[int]        =			giou_cost
          # Loss coefficients
          snake_case			:      str        =			mask_loss_coefficient
          snake_case			:      Any        =			dice_loss_coefficient
          snake_case			:      List[Any]        =			bbox_loss_coefficient
          snake_case			:      List[Any]        =			giou_loss_coefficient
          snake_case			:      List[str]        =			eos_coefficient
          snake_case			:      Optional[Any]        =			focal_alpha
          super().__init__(is_encoder_decoder=__a							,**__a							)







     @property
     def 			snake_case_      (				self							)      ->				int:
          return self.encoder_attention_heads







     @property
     def 			snake_case_      (				self							)      ->				int:
          return self.d_model







     def 			snake_case_      (				self							)      ->				List[str]:
          snake_case			:      List[str]        =			copy.deepcopy(self.__dict__							)
          snake_case			:      List[str]        =			self.backbone_config.to_dict()
          snake_case			:      List[Any]        =			self.__class__.model_type
          return output



