






'''simple docstring'''


import copy

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


lowerCamelCase_				: str    	=							logging.get_logger(__name__)

lowerCamelCase_				: Optional[int]    	=							{
    '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


			'''simple docstring'''





			__a							:							Tuple					     =					"deformable_detr"
			__a							:							str					     =					{
			    "hidden_size": "d_model",
			    "num_attention_heads": "encoder_attention_heads",
			}






			def __init__(   self							:						List[Any] ,      lowercase							:						List[Any]=True ,      lowercase							:						Tuple=None ,      lowercase							:						Tuple=3 ,      lowercase							:						List[str]=3_0_0 ,      lowercase							:						List[Any]=1_0_2_4 ,      lowercase							:						List[Any]=6 ,      lowercase							:						Tuple=1_0_2_4 ,      lowercase							:						Union[str, Any]=8 ,      lowercase							:						Optional[Any]=6 ,      lowercase							:						Tuple=1_0_2_4 ,      lowercase							:						Any=8 ,      lowercase							:						List[str]=0.0 ,      lowercase							:						Any=True ,      lowercase							:						Union[str, Any]="relu" ,      lowercase							:						Dict=2_5_6 ,      lowercase							:						Optional[int]=0.1 ,      lowercase							:						Optional[int]=0.0 ,      lowercase							:						List[str]=0.0 ,      lowercase							:						Any=0.0_2 ,      lowercase							:						Optional[int]=1.0 ,      lowercase							:						Tuple=True ,      lowercase							:						Optional[int]=False ,      lowercase							:						Any="sine" ,      lowercase							:						List[str]="resnet50" ,      lowercase							:						List[str]=True ,      lowercase							:						Optional[int]=False ,      lowercase							:						int=4 ,      lowercase							:						str=4 ,      lowercase							:						Dict=4 ,      lowercase							:						int=False ,      lowercase							:						List[Any]=3_0_0 ,      lowercase							:						List[Any]=False ,      lowercase							:						Dict=1 ,      lowercase							:						int=5 ,      lowercase							:						List[Any]=2 ,      lowercase							:						List[str]=1 ,      lowercase							:						Tuple=1 ,      lowercase							:						Dict=5 ,      lowercase							:						Dict=2 ,      lowercase							:						Dict=0.1 ,      lowercase							:						List[str]=0.2_5 ,      lowercase							:						Tuple=False ,      **lowercase							:						str ,      )							->    str:

									'''simple docstring'''







									if backbone_config is not None and use_timm_backbone:
															raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`."""			)

									if not use_timm_backbone:
															if backbone_config is None:
																					logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""			)
																					UpperCamelCase__         = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]			)
															elif isinstance(lowercase ,      lowercase			):
																					UpperCamelCase__         = backbone_config.get("""model_type"""			)
																					UpperCamelCase__         = CONFIG_MAPPING[backbone_model_type]
																					UpperCamelCase__         = config_class.from_dict(lowercase			)
									UpperCamelCase__         = use_timm_backbone
									UpperCamelCase__         = backbone_config
									UpperCamelCase__         = num_channels
									UpperCamelCase__         = num_queries
									UpperCamelCase__         = max_position_embeddings
									UpperCamelCase__         = d_model
									UpperCamelCase__         = encoder_ffn_dim
									UpperCamelCase__         = encoder_layers
									UpperCamelCase__         = encoder_attention_heads
									UpperCamelCase__         = decoder_ffn_dim
									UpperCamelCase__         = decoder_layers
									UpperCamelCase__         = decoder_attention_heads
									UpperCamelCase__         = dropout
									UpperCamelCase__         = attention_dropout
									UpperCamelCase__         = activation_dropout
									UpperCamelCase__         = activation_function
									UpperCamelCase__         = init_std
									UpperCamelCase__         = init_xavier_std
									UpperCamelCase__         = encoder_layerdrop
									UpperCamelCase__         = auxiliary_loss
									UpperCamelCase__         = position_embedding_type
									UpperCamelCase__         = backbone
									UpperCamelCase__         = use_pretrained_backbone
									UpperCamelCase__         = dilation
									# deformable attributes
									UpperCamelCase__         = num_feature_levels
									UpperCamelCase__         = encoder_n_points
									UpperCamelCase__         = decoder_n_points
									UpperCamelCase__         = two_stage
									UpperCamelCase__         = two_stage_num_proposals
									UpperCamelCase__         = with_box_refine
									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
									UpperCamelCase__         = class_cost
									UpperCamelCase__         = bbox_cost
									UpperCamelCase__         = giou_cost
									# Loss coefficients
									UpperCamelCase__         = mask_loss_coefficient
									UpperCamelCase__         = dice_loss_coefficient
									UpperCamelCase__         = bbox_loss_coefficient
									UpperCamelCase__         = giou_loss_coefficient
									UpperCamelCase__         = eos_coefficient
									UpperCamelCase__         = focal_alpha
									UpperCamelCase__         = disable_custom_kernels
									super().__init__(is_encoder_decoder=lowercase ,      **lowercase			)






			@property
			def 				A      (   self							:						str			)							->    int:

									'''simple docstring'''







									return self.encoder_attention_heads






			@property
			def 				A      (   self							:						Tuple			)							->    int:

									'''simple docstring'''







									return self.d_model







			def 				A      (   self							:						Dict			)							->    Optional[Any]:

									'''simple docstring'''







									UpperCamelCase__         = copy.deepcopy(self.__dict__			)
									if self.backbone_config is not None:
															UpperCamelCase__         = self.backbone_config.to_dict()
									UpperCamelCase__         = self.__class__.model_type
									return output








'''simple docstring'''


import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
class    _SCREAMING_SNAKE_CASE							(		unittest.TestCase	):


			'''simple docstring'''





			def 				A      (   self							:						Any			)							->    Any:

									'''simple docstring'''







									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()






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

									'''simple docstring'''







									torch.manual_seed(0			)
									UpperCamelCase__         = UNetaDModel(
									    sample_size=(3_2, 6_4) ,      in_channels=1 ,      out_channels=1 ,      layers_per_block=2 ,      block_out_channels=(1_2_8, 1_2_8) ,      down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") ,      up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") ,      )
									return model






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

									'''simple docstring'''







									torch.manual_seed(0			)
									UpperCamelCase__         = UNetaDConditionModel(
									    sample_size=(6_4, 3_2) ,      in_channels=1 ,      out_channels=1 ,      layers_per_block=2 ,      block_out_channels=(1_2_8, 1_2_8) ,      down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") ,      up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") ,      cross_attention_dim=1_0 ,      )
									return model






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

									'''simple docstring'''







									torch.manual_seed(0			)
									UpperCamelCase__         = AutoencoderKL(
									    sample_size=(1_2_8, 6_4) ,      in_channels=1 ,      out_channels=1 ,      latent_channels=1 ,      layers_per_block=2 ,      block_out_channels=(1_2_8, 1_2_8) ,      down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") ,      up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") ,      )
									UpperCamelCase__         = UNetaDModel(
									    sample_size=(6_4, 3_2) ,      in_channels=1 ,      out_channels=1 ,      layers_per_block=2 ,      block_out_channels=(1_2_8, 1_2_8) ,      down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") ,      up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") ,      )
									return vqvae, unet







			@slow
			def 				A      (   self							:						Tuple			)							->    List[str]:

									'''simple docstring'''







									UpperCamelCase__         = """cpu"""  # ensure determinism for the device-dependent torch.Generator
									UpperCamelCase__         = Mel(
									    x_res=self.dummy_unet.config.sample_size[1] ,      y_res=self.dummy_unet.config.sample_size[0] ,      )

									UpperCamelCase__         = DDPMScheduler()
									UpperCamelCase__         = AudioDiffusionPipeline(vqvae=lowercase ,      unet=self.dummy_unet ,      mel=lowercase ,      scheduler=lowercase			)
									UpperCamelCase__         = pipe.to(lowercase			)
									pipe.set_progress_bar_config(disable=lowercase			)

									UpperCamelCase__         = torch.Generator(device=lowercase			).manual_seed(4_2			)
									UpperCamelCase__         = pipe(generator=lowercase ,      steps=4			)
									UpperCamelCase__         = output.audios[0]
									UpperCamelCase__         = output.images[0]

									UpperCamelCase__         = torch.Generator(device=lowercase			).manual_seed(4_2			)
									UpperCamelCase__         = pipe(generator=lowercase ,      steps=4 ,      return_dict=lowercase			)
									UpperCamelCase__         = output[0][0]

									assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
									assert (
									    image.height == self.dummy_unet.config.sample_size[0]
									    and image.width == self.dummy_unet.config.sample_size[1]
									)
									UpperCamelCase__         = np.frombuffer(image.tobytes() ,      dtype="""uint8"""			)[:1_0]
									UpperCamelCase__         = np.frombuffer(image_from_tuple.tobytes() ,      dtype="""uint8"""			)[:1_0]
									UpperCamelCase__         = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7]			)

									assert np.abs(image_slice.flatten() - expected_slice			).max() == 0
									assert np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() == 0

									UpperCamelCase__         = Mel(
									    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] ,      y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] ,      )

									UpperCamelCase__         = DDIMScheduler()
									UpperCamelCase__         = self.dummy_vqvae_and_unet
									UpperCamelCase__         = AudioDiffusionPipeline(
									    vqvae=self.dummy_vqvae_and_unet[0] ,      unet=dummy_vqvae_and_unet[1] ,      mel=lowercase ,      scheduler=lowercase			)
									UpperCamelCase__         = pipe.to(lowercase			)
									pipe.set_progress_bar_config(disable=lowercase			)

									np.random.seed(0			)
									UpperCamelCase__         = np.random.uniform(-1 ,      1 ,      ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)			)
									UpperCamelCase__         = torch.Generator(device=lowercase			).manual_seed(4_2			)
									UpperCamelCase__         = pipe(raw_audio=lowercase ,      generator=lowercase ,      start_step=5 ,      steps=1_0			)
									UpperCamelCase__         = output.images[0]

									assert (
									    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
									    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
									)
									UpperCamelCase__         = np.frombuffer(image.tobytes() ,      dtype="""uint8"""			)[:1_0]
									UpperCamelCase__         = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1]			)

									assert np.abs(image_slice.flatten() - expected_slice			).max() == 0

									UpperCamelCase__         = self.dummy_unet_condition
									UpperCamelCase__         = AudioDiffusionPipeline(
									    vqvae=self.dummy_vqvae_and_unet[0] ,      unet=lowercase ,      mel=lowercase ,      scheduler=lowercase			)
									UpperCamelCase__         = pipe.to(lowercase			)
									pipe.set_progress_bar_config(disable=lowercase			)

									np.random.seed(0			)
									UpperCamelCase__         = torch.rand((1, 1, 1_0)			)
									UpperCamelCase__         = pipe(generator=lowercase ,      encoding=lowercase			)
									UpperCamelCase__         = output.images[0]
									UpperCamelCase__         = np.frombuffer(image.tobytes() ,      dtype="""uint8"""			)[:1_0]
									UpperCamelCase__         = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1]			)

									assert np.abs(image_slice.flatten() - expected_slice			).max() == 0
@slow
@require_torch_gpu
class    _SCREAMING_SNAKE_CASE							(		unittest.TestCase	):


			'''simple docstring'''





			def 				A      (   self							:						int			)							->    str:

									'''simple docstring'''







									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







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

									'''simple docstring'''







									UpperCamelCase__         = torch_device

									UpperCamelCase__         = DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256"""			)
									UpperCamelCase__         = pipe.to(lowercase			)
									pipe.set_progress_bar_config(disable=lowercase			)

									UpperCamelCase__         = torch.Generator(device=lowercase			).manual_seed(4_2			)
									UpperCamelCase__         = pipe(generator=lowercase			)
									UpperCamelCase__         = output.audios[0]
									UpperCamelCase__         = output.images[0]

									assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
									assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
									UpperCamelCase__         = np.frombuffer(image.tobytes() ,      dtype="""uint8"""			)[:1_0]
									UpperCamelCase__         = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6]			)

									assert np.abs(image_slice.flatten() - expected_slice			).max() == 0
