


import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


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






class _lowerCamelCase(						_a   ):
       def __init__(					self,      *lowerCamelCase,      lowerCamelCase=None,      lowerCamelCase=None,      **lowerCamelCase)       ->   List[str]:




           """simple docstring"""

           super().__init__(*lowerCamelCase,      **lowerCamelCase)
           _lowercase       :							Union[str, Any]      		=		eval_examples
           _lowercase       :							Dict      		=		post_process_function
       def 			UpperCamelCase     (					self,      lowerCamelCase=None,      lowerCamelCase=None,      lowerCamelCase=None,      lowerCamelCase = "eval")       ->   Any:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		self.eval_dataset if eval_dataset is None else eval_dataset
           _lowercase       :							str      		=		self.get_eval_dataloader(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		self.eval_examples if eval_examples is None else eval_examples

           # Temporarily disable metric computation, we will do it in the loop here.
           _lowercase       :							List[str]      		=		self.compute_metrics
           _lowercase       :							Dict      		=		None
           _lowercase       :							Optional[int]      		=		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           _lowercase       :							Optional[Any]      		=		time.time()
           try:
               _lowercase       :							Any      		=		eval_loop(
                   lowerCamelCase,      description='Evaluation',      prediction_loss_only=True if compute_metrics is None else None,      ignore_keys=lowerCamelCase,      metric_key_prefix=lowerCamelCase,      )
           finally:
               _lowercase       :							List[str]      		=		compute_metrics
           _lowercase       :							Any      		=		self.args.eval_batch_size * self.args.world_size
           if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
               start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
           output.metrics.update(
               speed_metrics(
                   lowerCamelCase,      lowerCamelCase,      num_samples=output.num_samples,      num_steps=math.ceil(output.num_samples / total_batch_size),      ))
           if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
               # Only the main node write the results by default
               _lowercase       :							Any      		=		self.post_process_function(lowerCamelCase,      lowerCamelCase,      output.predictions)
               _lowercase       :							Optional[Any]      		=		self.compute_metrics(lowerCamelCase)

               # Prefix all keys with metric_key_prefix + '_'
               for key in list(metrics.keys()):
                   if not key.startswith(F'''{metric_key_prefix}_'''):
                       _lowercase       :							List[str]      		=		metrics.pop(lowerCamelCase)
               metrics.update(output.metrics)
           else:
               _lowercase       :							Tuple      		=		output.metrics

           if self.args.should_log:
               # Only the main node log the results by default
               self.log(lowerCamelCase)

           if self.args.tpu_metrics_debug or self.args.debug:
               # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
               xm.master_print(met.metrics_report())

           _lowercase       :							List[Any]      		=		self.callback_handler.on_evaluate(self.args,      self.state,      self.control,      lowerCamelCase)
           return metrics




       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      lowerCamelCase = "test")       ->   str:




           """simple docstring"""

           _lowercase       :							str      		=		self.get_test_dataloader(lowerCamelCase)

           # Temporarily disable metric computation, we will do it in the loop here.
           _lowercase       :							str      		=		self.compute_metrics
           _lowercase       :							Tuple      		=		None
           _lowercase       :							Union[str, Any]      		=		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           _lowercase       :							Optional[int]      		=		time.time()
           try:
               _lowercase       :							Optional[Any]      		=		eval_loop(
                   lowerCamelCase,      description='Prediction',      prediction_loss_only=True if compute_metrics is None else None,      ignore_keys=lowerCamelCase,      metric_key_prefix=lowerCamelCase,      )
           finally:
               _lowercase       :							str      		=		compute_metrics
           _lowercase       :							Union[str, Any]      		=		self.args.eval_batch_size * self.args.world_size
           if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
               start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
           output.metrics.update(
               speed_metrics(
                   lowerCamelCase,      lowerCamelCase,      num_samples=output.num_samples,      num_steps=math.ceil(output.num_samples / total_batch_size),      ))

           if self.post_process_function is None or self.compute_metrics is None:
               return output

           _lowercase       :							Optional[int]      		=		self.post_process_function(lowerCamelCase,      lowerCamelCase,      output.predictions,      'predict')
           _lowercase       :							Optional[int]      		=		self.compute_metrics(lowerCamelCase)

           # Prefix all keys with metric_key_prefix + '_'
           for key in list(metrics.keys()):
               if not key.startswith(F'''{metric_key_prefix}_'''):
                   _lowercase       :							str      		=		metrics.pop(lowerCamelCase)
           metrics.update(output.metrics)
           return PredictionOutput(predictions=predictions.predictions,      label_ids=predictions.label_ids,      metrics=lowerCamelCase)






import copy

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


SCREAMING_SNAKE_CASE       :      int												= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE       :      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 _lowerCamelCase(						_a   ):
       lowercase_ :	Dict     =			"""deformable_detr"""
       lowercase_ :	int     =			{
           """hidden_size""": """d_model""",
           """num_attention_heads""": """encoder_attention_heads""",
       }
       def __init__(					self,      lowerCamelCase=True,      lowerCamelCase=None,      lowerCamelCase=3,      lowerCamelCase=3_00,      lowerCamelCase=10_24,      lowerCamelCase=6,      lowerCamelCase=10_24,      lowerCamelCase=8,      lowerCamelCase=6,      lowerCamelCase=10_24,      lowerCamelCase=8,      lowerCamelCase=0.0,      lowerCamelCase=True,      lowerCamelCase="relu",      lowerCamelCase=2_56,      lowerCamelCase=0.1,      lowerCamelCase=0.0,      lowerCamelCase=0.0,      lowerCamelCase=0.0_2,      lowerCamelCase=1.0,      lowerCamelCase=True,      lowerCamelCase=False,      lowerCamelCase="sine",      lowerCamelCase="resnet50",      lowerCamelCase=True,      lowerCamelCase=False,      lowerCamelCase=4,      lowerCamelCase=4,      lowerCamelCase=4,      lowerCamelCase=False,      lowerCamelCase=3_00,      lowerCamelCase=False,      lowerCamelCase=1,      lowerCamelCase=5,      lowerCamelCase=2,      lowerCamelCase=1,      lowerCamelCase=1,      lowerCamelCase=5,      lowerCamelCase=2,      lowerCamelCase=0.1,      lowerCamelCase=0.2_5,      lowerCamelCase=False,      **lowerCamelCase,      )       ->   Optional[int]:




           """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.')
                   _lowercase       :							List[str]      		=		CONFIG_MAPPING['resnet'](out_features=['stage4'])
               elif isinstance(lowerCamelCase,      lowerCamelCase):
                   _lowercase       :							List[str]      		=		backbone_config.get('model_type')
                   _lowercase       :							str      		=		CONFIG_MAPPING[backbone_model_type]
                   _lowercase       :							Optional[int]      		=		config_class.from_dict(lowerCamelCase)
           _lowercase       :							Tuple      		=		use_timm_backbone
           _lowercase       :							List[str]      		=		backbone_config
           _lowercase       :							Tuple      		=		num_channels
           _lowercase       :							Optional[Any]      		=		num_queries
           _lowercase       :							Optional[Any]      		=		max_position_embeddings
           _lowercase       :							Optional[int]      		=		d_model
           _lowercase       :							int      		=		encoder_ffn_dim
           _lowercase       :							List[Any]      		=		encoder_layers
           _lowercase       :							str      		=		encoder_attention_heads
           _lowercase       :							str      		=		decoder_ffn_dim
           _lowercase       :							Optional[Any]      		=		decoder_layers
           _lowercase       :							List[str]      		=		decoder_attention_heads
           _lowercase       :							Optional[int]      		=		dropout
           _lowercase       :							Optional[Any]      		=		attention_dropout
           _lowercase       :							int      		=		activation_dropout
           _lowercase       :							Any      		=		activation_function
           _lowercase       :							Optional[int]      		=		init_std
           _lowercase       :							int      		=		init_xavier_std
           _lowercase       :							Union[str, Any]      		=		encoder_layerdrop
           _lowercase       :							Tuple      		=		auxiliary_loss
           _lowercase       :							Union[str, Any]      		=		position_embedding_type
           _lowercase       :							str      		=		backbone
           _lowercase       :							List[Any]      		=		use_pretrained_backbone
           _lowercase       :							Any      		=		dilation
           # deformable attributes
           _lowercase       :							Any      		=		num_feature_levels
           _lowercase       :							Dict      		=		encoder_n_points
           _lowercase       :							Dict      		=		decoder_n_points
           _lowercase       :							Dict      		=		two_stage
           _lowercase       :							Union[str, Any]      		=		two_stage_num_proposals
           _lowercase       :							str      		=		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
           _lowercase       :							Tuple      		=		class_cost
           _lowercase       :							int      		=		bbox_cost
           _lowercase       :							Optional[int]      		=		giou_cost
           # Loss coefficients
           _lowercase       :							Optional[Any]      		=		mask_loss_coefficient
           _lowercase       :							Dict      		=		dice_loss_coefficient
           _lowercase       :							Tuple      		=		bbox_loss_coefficient
           _lowercase       :							Optional[int]      		=		giou_loss_coefficient
           _lowercase       :							Union[str, Any]      		=		eos_coefficient
           _lowercase       :							Union[str, Any]      		=		focal_alpha
           _lowercase       :							Dict      		=		disable_custom_kernels
           super().__init__(is_encoder_decoder=lowerCamelCase,      **lowerCamelCase)
       @property
       def 			UpperCamelCase     (					self)       ->   int:




           """simple docstring"""

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




           """simple docstring"""

           return self.d_model




       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		copy.deepcopy(self.__dict__)
           if self.backbone_config is not None:
               _lowercase       :							Union[str, Any]      		=		self.backbone_config.to_dict()
           _lowercase       :							Tuple      		=		self.__class__.model_type
           return output


