


'''simple docstring'''






import copy

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


__A	:	str     =     logging.get_logger(__name__)

__A	:	List[str]     =     {
    '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 						__UpperCamelCase	(						lowercase__							):
							lowercase			:		Optional[Any]   		=  'deformable_detr'
							lowercase			:		Optional[int]   		=  {
							    'hidden_size': 'd_model',
							    'num_attention_heads': 'encoder_attention_heads',
							}





							def __init__(  self		:int  ,_UpperCamelCase		:Optional[int]=True  ,_UpperCamelCase		:List[Any]=None  ,_UpperCamelCase		:List[str]=3  ,_UpperCamelCase		:Any=3_0_0  ,_UpperCamelCase		:Any=1_0_2_4  ,_UpperCamelCase		:str=6  ,_UpperCamelCase		:List[str]=1_0_2_4  ,_UpperCamelCase		:int=8  ,_UpperCamelCase		:Optional[Any]=6  ,_UpperCamelCase		:Any=1_0_2_4  ,_UpperCamelCase		:Union[str, Any]=8  ,_UpperCamelCase		:List[Any]=0.0  ,_UpperCamelCase		:Optional[int]=True  ,_UpperCamelCase		:Optional[int]="relu"  ,_UpperCamelCase		:str=2_5_6  ,_UpperCamelCase		:Optional[Any]=0.1  ,_UpperCamelCase		:List[Any]=0.0  ,_UpperCamelCase		:List[str]=0.0  ,_UpperCamelCase		:int=0.02  ,_UpperCamelCase		:List[str]=1.0  ,_UpperCamelCase		:Optional[Any]=True  ,_UpperCamelCase		:Optional[int]=False  ,_UpperCamelCase		:Optional[int]="sine"  ,_UpperCamelCase		:Tuple="resnet50"  ,_UpperCamelCase		:Any=True  ,_UpperCamelCase		:Dict=False  ,_UpperCamelCase		:List[Any]=4  ,_UpperCamelCase		:Optional[Any]=4  ,_UpperCamelCase		:Union[str, Any]=4  ,_UpperCamelCase		:Optional[int]=False  ,_UpperCamelCase		:Optional[int]=3_0_0  ,_UpperCamelCase		:Optional[Any]=False  ,_UpperCamelCase		:Optional[int]=1  ,_UpperCamelCase		:Optional[Any]=5  ,_UpperCamelCase		:Union[str, Any]=2  ,_UpperCamelCase		:List[Any]=1  ,_UpperCamelCase		:List[str]=1  ,_UpperCamelCase		:Union[str, Any]=5  ,_UpperCamelCase		:List[Any]=2  ,_UpperCamelCase		:str=0.1  ,_UpperCamelCase		:Optional[int]=0.25  ,_UpperCamelCase		:Optional[int]=False  ,**_UpperCamelCase		:str  ,):
									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."""			)
													snake_case_		:							Union[str, Any]			       =						CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]			)
											elif isinstance(_UpperCamelCase  ,_UpperCamelCase			):
													snake_case_		:							str			       =						backbone_config.get("""model_type"""			)
													snake_case_		:							Union[str, Any]			       =						CONFIG_MAPPING[backbone_model_type]
													snake_case_		:							Tuple			       =						config_class.from_dict(_UpperCamelCase			)
									snake_case_		:							Tuple			       =						use_timm_backbone
									snake_case_		:							Any			       =						backbone_config
									snake_case_		:							Union[str, Any]			       =						num_channels
									snake_case_		:							Any			       =						num_queries
									snake_case_		:							int			       =						max_position_embeddings
									snake_case_		:							str			       =						d_model
									snake_case_		:							Optional[Any]			       =						encoder_ffn_dim
									snake_case_		:							int			       =						encoder_layers
									snake_case_		:							Any			       =						encoder_attention_heads
									snake_case_		:							List[Any]			       =						decoder_ffn_dim
									snake_case_		:							int			       =						decoder_layers
									snake_case_		:							Optional[int]			       =						decoder_attention_heads
									snake_case_		:							List[Any]			       =						dropout
									snake_case_		:							int			       =						attention_dropout
									snake_case_		:							List[Any]			       =						activation_dropout
									snake_case_		:							str			       =						activation_function
									snake_case_		:							Union[str, Any]			       =						init_std
									snake_case_		:							Any			       =						init_xavier_std
									snake_case_		:							List[str]			       =						encoder_layerdrop
									snake_case_		:							List[Any]			       =						auxiliary_loss
									snake_case_		:							Any			       =						position_embedding_type
									snake_case_		:							List[Any]			       =						backbone
									snake_case_		:							int			       =						use_pretrained_backbone
									snake_case_		:							Union[str, Any]			       =						dilation
									# deformable attributes
									snake_case_		:							List[Any]			       =						num_feature_levels
									snake_case_		:							str			       =						encoder_n_points
									snake_case_		:							Tuple			       =						decoder_n_points
									snake_case_		:							str			       =						two_stage
									snake_case_		:							Union[str, Any]			       =						two_stage_num_proposals
									snake_case_		:							Optional[int]			       =						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
									snake_case_		:							int			       =						class_cost
									snake_case_		:							Optional[int]			       =						bbox_cost
									snake_case_		:							List[Any]			       =						giou_cost
									# Loss coefficients
									snake_case_		:							Optional[Any]			       =						mask_loss_coefficient
									snake_case_		:							Dict			       =						dice_loss_coefficient
									snake_case_		:							Dict			       =						bbox_loss_coefficient
									snake_case_		:							Tuple			       =						giou_loss_coefficient
									snake_case_		:							Union[str, Any]			       =						eos_coefficient
									snake_case_		:							Union[str, Any]			       =						focal_alpha
									snake_case_		:							Optional[Any]			       =						disable_custom_kernels
									super().__init__(is_encoder_decoder=_UpperCamelCase  ,**_UpperCamelCase			)





							@property
							def 		a__   (  self		:Tuple			):
									return self.encoder_attention_heads





							@property
							def 		a__   (  self		:Union[str, Any]			):
									return self.d_model





							def 		a__   (  self		:int			):
									snake_case_		:							Any			       =						copy.deepcopy(self.__dict__			)
									if self.backbone_config is not None:
											snake_case_		:							List[Any]			       =						self.backbone_config.to_dict()
									snake_case_		:							Any			       =						self.__class__.model_type
									return output



'''simple docstring'''






import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 						__UpperCamelCase	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		List[str]   		=  KandinskyVaaPriorPipeline
							lowercase			:		Optional[Any]   		=  ['prompt']
							lowercase			:		Dict   		=  ['prompt', 'negative_prompt']
							lowercase			:		Dict   		=  [
							    'num_images_per_prompt',
							    'generator',
							    'num_inference_steps',
							    'latents',
							    'negative_prompt',
							    'guidance_scale',
							    'output_type',
							    'return_dict',
							]
							lowercase			:		int   		=  False





							@property
							def 		a__   (  self		:int			):
									return 3_2





							@property
							def 		a__   (  self		:Any			):
									return 3_2





							@property
							def 		a__   (  self		:Union[str, Any]			):
									return self.time_input_dim





							@property
							def 		a__   (  self		:int			):
									return self.time_input_dim * 4





							@property
							def 		a__   (  self		:Dict			):
									return 1_0_0





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							List[Any]			       =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
									return tokenizer





							@property
							def 		a__   (  self		:int			):
									torch.manual_seed(0			)
									snake_case_		:							Optional[Any]			       =						CLIPTextConfig(
									    bos_token_id=0  ,eos_token_id=2  ,hidden_size=self.text_embedder_hidden_size  ,projection_dim=self.text_embedder_hidden_size  ,intermediate_size=3_7  ,layer_norm_eps=1E-0_5  ,num_attention_heads=4  ,num_hidden_layers=5  ,pad_token_id=1  ,vocab_size=1_0_0_0  ,)
									return CLIPTextModelWithProjection(_UpperCamelCase			)





							@property
							def 		a__   (  self		:Dict			):
									torch.manual_seed(0			)

									snake_case_		:							Tuple			       =						{
									    """num_attention_heads""": 2,
									    """attention_head_dim""": 1_2,
									    """embedding_dim""": self.text_embedder_hidden_size,
									    """num_layers""": 1,
									}

									snake_case_		:							int			       =						PriorTransformer(**_UpperCamelCase			)
									# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
									snake_case_		:							Any			       =						nn.Parameter(torch.ones(model.clip_std.shape			)			)
									return model





							@property
							def 		a__   (  self		:Optional[int]			):
									torch.manual_seed(0			)
									snake_case_		:							Any			       =						CLIPVisionConfig(
									    hidden_size=self.text_embedder_hidden_size  ,image_size=2_2_4  ,projection_dim=self.text_embedder_hidden_size  ,intermediate_size=3_7  ,num_attention_heads=4  ,num_channels=3  ,num_hidden_layers=5  ,patch_size=1_4  ,)

									snake_case_		:							Optional[Any]			       =						CLIPVisionModelWithProjection(_UpperCamelCase			)
									return model





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						CLIPImageProcessor(
									    crop_size=2_2_4  ,do_center_crop=_UpperCamelCase  ,do_normalize=_UpperCamelCase  ,do_resize=_UpperCamelCase  ,image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]  ,image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]  ,resample=3  ,size=2_2_4  ,)

									return image_processor





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Tuple			       =						self.dummy_prior
									snake_case_		:							Any			       =						self.dummy_image_encoder
									snake_case_		:							Optional[int]			       =						self.dummy_text_encoder
									snake_case_		:							Any			       =						self.dummy_tokenizer
									snake_case_		:							Union[str, Any]			       =						self.dummy_image_processor

									snake_case_		:							Tuple			       =						UnCLIPScheduler(
									    variance_type="""fixed_small_log"""  ,prediction_type="""sample"""  ,num_train_timesteps=1_0_0_0  ,clip_sample=_UpperCamelCase  ,clip_sample_range=10.0  ,)

									snake_case_		:							Tuple			       =						{
									    """prior""": prior,
									    """image_encoder""": image_encoder,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """scheduler""": scheduler,
									    """image_processor""": image_processor,
									}

									return components





							def 		a__   (  self		:Dict  ,_UpperCamelCase		:str  ,_UpperCamelCase		:Union[str, Any]=0			):
									if str(_UpperCamelCase			).startswith("""mps"""			):
											snake_case_		:							Optional[int]			       =						torch.manual_seed(_UpperCamelCase			)
									else:
											snake_case_		:							int			       =						torch.Generator(device=_UpperCamelCase			).manual_seed(_UpperCamelCase			)
									snake_case_		:							Dict			       =						{
									    """prompt""": """horse""",
									    """generator""": generator,
									    """guidance_scale""": 4.0,
									    """num_inference_steps""": 2,
									    """output_type""": """np""",
									}
									return inputs





							def 		a__   (  self		:int			):
									snake_case_		:							Union[str, Any]			       =						"""cpu"""

									snake_case_		:							int			       =						self.get_dummy_components()

									snake_case_		:							int			       =						self.pipeline_class(**_UpperCamelCase			)
									snake_case_		:							Union[str, Any]			       =						pipe.to(_UpperCamelCase			)

									pipe.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Any			       =						pipe(**self.get_dummy_inputs(_UpperCamelCase			)			)
									snake_case_		:							List[Any]			       =						output.image_embeds

									snake_case_		:							List[Any]			       =						pipe(
									    **self.get_dummy_inputs(_UpperCamelCase			)  ,return_dict=_UpperCamelCase  ,)[0]

									snake_case_		:							Dict			       =						image[0, -1_0:]
									snake_case_		:							Optional[Any]			       =						image_from_tuple[0, -1_0:]

									assert image.shape == (1, 3_2)

									snake_case_		:							Optional[int]			       =						np.array(
									    [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]			)

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





							@skip_mps
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						torch_device == """cpu"""
									snake_case_		:							Any			       =						True
									snake_case_		:							Dict			       =						False

									self._test_inference_batch_single_identical(
									    test_max_difference=_UpperCamelCase  ,relax_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)





							@skip_mps
							def 		a__   (  self		:str			):
									snake_case_		:							str			       =						torch_device == """cpu"""
									snake_case_		:							List[str]			       =						False

									self._test_attention_slicing_forward_pass(
									    test_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)