





import copy

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


__UpperCAmelCase       :   int				       =							logging.get_logger(__name__)

__UpperCAmelCase       :   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     __snake_case       (							__lowerCamelCase			):





       '''simple docstring'''







       lowerCAmelCase__      		=     """deformable_detr"""
       lowerCAmelCase__      		=     {
           """hidden_size""": """d_model""",
           """num_attention_heads""": """encoder_attention_heads""",
       }




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




       @property
       def 							UpperCAmelCase__ (  self :    str		):
         return self.encoder_attention_heads




       @property
       def 							UpperCAmelCase__ (  self :    List[Any]		):
         return self.d_model






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













import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
      import tensorflow as tf

      from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments







@require_tf
class     __snake_case       (							unittest.TestCase			):





       '''simple docstring'''







       def 							UpperCAmelCase__ (  self :    Any							,				A :    Union[str, Any]		):
         for model_result in results.values():
           for batch_size, sequence_length in zip(model_result["""bs"""]							,				model_result["""ss"""]		):
             __snake_case:						Dict   =						model_result["""result"""][batch_size][sequence_length]
             self.assertIsNotNone(A		)




       def 							UpperCAmelCase__ (  self :    List[Any]		):
         __snake_case:						List[Any]   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						Union[str, Any]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				eager_mode=A							,				multi_process=A							,				)
         __snake_case:						Dict   =						TensorFlowBenchmark(A		)
         __snake_case:						List[str]   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         __snake_case:						Optional[int]   =						"""sgugger/tiny-distilbert-classification"""
         __snake_case:						str   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				only_pretrain_model=A							,				)
         __snake_case:						Any   =						TensorFlowBenchmark(A		)
         __snake_case:						List[Any]   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    int		):
         __snake_case:						Dict   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						Union[str, Any]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				)
         __snake_case:						int   =						TensorFlowBenchmark(A		)
         __snake_case:						str   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    List[Any]		):
         __snake_case:						List[Any]   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						int   =						AutoConfig.from_pretrained(A		)
         __snake_case:						Optional[Any]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				eager_mode=A							,				multi_process=A							,				)
         __snake_case:						Union[str, Any]   =						TensorFlowBenchmark(A							,				[config]		)
         __snake_case:						Tuple   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    Any		):
         __snake_case:						Optional[int]   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						Tuple   =						AutoConfig.from_pretrained(A		)
         __snake_case:						Union[str, Any]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				)
         __snake_case:						str   =						TensorFlowBenchmark(A							,				[config]		)
         __snake_case:						str   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    Any		):
         __snake_case:						Tuple   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						str   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				)
         __snake_case:						Tuple   =						TensorFlowBenchmark(A		)
         __snake_case:						Tuple   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_train_result		)
         self.check_results_dict_not_empty(results.memory_train_result		)




       def 							UpperCAmelCase__ (  self :    int		):
         __snake_case:						Dict   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						Union[str, Any]   =						AutoConfig.from_pretrained(A		)
         __snake_case:						Optional[int]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				)
         __snake_case:						List[str]   =						TensorFlowBenchmark(A							,				[config]		)
         __snake_case:						Dict   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_train_result		)
         self.check_results_dict_not_empty(results.memory_train_result		)




       def 							UpperCAmelCase__ (  self :    List[str]		):
         __snake_case:						List[Any]   =						"""patrickvonplaten/t5-tiny-random"""
         __snake_case:						List[str]   =						AutoConfig.from_pretrained(A		)
         __snake_case:						List[str]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				multi_process=A							,				)
         __snake_case:						Optional[int]   =						TensorFlowBenchmark(A							,				configs=[config]		)
         __snake_case:						Tuple   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("""GPU"""		)		) == 0							,				"""Cannot do xla on CPU."""		)
       def 							UpperCAmelCase__ (  self :    Optional[Any]		):
         __snake_case:						Optional[Any]   =						"""sshleifer/tiny-gpt2"""
         __snake_case:						List[Any]   =						TensorFlowBenchmarkArguments(
             models=[MODEL_ID]							,				training=A							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				use_xla=A							,				multi_process=A							,				)
         __snake_case:						Union[str, Any]   =						TensorFlowBenchmark(A		)
         __snake_case:						List[Any]   =						benchmark.run()
         self.check_results_dict_not_empty(results.time_inference_result		)
         self.check_results_dict_not_empty(results.memory_inference_result		)




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         __snake_case:						List[str]   =						"""sshleifer/tiny-gpt2"""
         with tempfile.TemporaryDirectory() as tmp_dir:
           __snake_case:						int   =						TensorFlowBenchmarkArguments(
               models=[MODEL_ID]							,				inference=A							,				save_to_csv=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				inference_time_csv_file=os.path.join(A							,				"""inf_time.csv"""		)							,				inference_memory_csv_file=os.path.join(A							,				"""inf_mem.csv"""		)							,				env_info_csv_file=os.path.join(A							,				"""env.csv"""		)							,				multi_process=A							,				)
           __snake_case:						Tuple   =						TensorFlowBenchmark(A		)
           benchmark.run()
           self.assertTrue(Path(os.path.join(A							,				"""inf_time.csv"""		)		).exists()		)
           self.assertTrue(Path(os.path.join(A							,				"""inf_mem.csv"""		)		).exists()		)
           self.assertTrue(Path(os.path.join(A							,				"""env.csv"""		)		).exists()		)






       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         __snake_case:						Any   =						"""sshleifer/tiny-gpt2"""

         def _check_summary_is_not_empty(A :    Union[str, Any]		):
           self.assertTrue(hasattr(A							,				"""sequential"""		)		)
           self.assertTrue(hasattr(A							,				"""cumulative"""		)		)
           self.assertTrue(hasattr(A							,				"""current"""		)		)
           self.assertTrue(hasattr(A							,				"""total"""		)		)

         with tempfile.TemporaryDirectory() as tmp_dir:
           __snake_case:						Union[str, Any]   =						TensorFlowBenchmarkArguments(
               models=[MODEL_ID]							,				inference=A							,				sequence_lengths=[8]							,				batch_sizes=[1]							,				log_filename=os.path.join(A							,				"""log.txt"""		)							,				log_print=A							,				trace_memory_line_by_line=A							,				eager_mode=A							,				multi_process=A							,				)
           __snake_case:						Dict   =						TensorFlowBenchmark(A		)
           __snake_case:						List[str]   =						benchmark.run()
           _check_summary_is_not_empty(result.inference_summary		)
           self.assertTrue(Path(os.path.join(A							,				"""log.txt"""		)		).exists()		)






