




import copy

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


UpperCamelCase__ :   str						=							logging.get_logger(__name__)

UpperCamelCase__ :   str						=							{
    '''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''',
}







class 				lowerCAmelCase_       (					lowerCamelCase_							):
				__a     :       Union[str, Any]						=     "deta"
				__a     :       Optional[int]						=     {
				    "hidden_size": "d_model",
				    "num_attention_heads": "encoder_attention_heads",
				}






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

							SCREAMING_SNAKE_CASE_   : str					  =      backbone_config
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      num_queries
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      max_position_embeddings
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      d_model
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      encoder_ffn_dim
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      encoder_layers
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      encoder_attention_heads
							SCREAMING_SNAKE_CASE_   : List[str]					  =      decoder_ffn_dim
							SCREAMING_SNAKE_CASE_   : List[str]					  =      decoder_layers
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      decoder_attention_heads
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      dropout
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      attention_dropout
							SCREAMING_SNAKE_CASE_   : int					  =      activation_dropout
							SCREAMING_SNAKE_CASE_   : Any					  =      activation_function
							SCREAMING_SNAKE_CASE_   : Any					  =      init_std
							SCREAMING_SNAKE_CASE_   : int					  =      init_xavier_std
							SCREAMING_SNAKE_CASE_   : Tuple					  =      encoder_layerdrop
							SCREAMING_SNAKE_CASE_   : Tuple					  =      auxiliary_loss
							SCREAMING_SNAKE_CASE_   : str					  =      position_embedding_type
							# deformable attributes
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      num_feature_levels
							SCREAMING_SNAKE_CASE_   : Any					  =      encoder_n_points
							SCREAMING_SNAKE_CASE_   : Dict					  =      decoder_n_points
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      two_stage
							SCREAMING_SNAKE_CASE_   : str					  =      two_stage_num_proposals
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      with_box_refine
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      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
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      class_cost
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      bbox_cost
							SCREAMING_SNAKE_CASE_   : Any					  =      giou_cost
							# Loss coefficients
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      mask_loss_coefficient
							SCREAMING_SNAKE_CASE_   : str					  =      dice_loss_coefficient
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      bbox_loss_coefficient
							SCREAMING_SNAKE_CASE_   : str					  =      giou_loss_coefficient
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      eos_coefficient
							SCREAMING_SNAKE_CASE_   : Tuple					  =      focal_alpha
							super().__init__(is_encoder_decoder=snake_case__      ,**snake_case__ )






				@property
				def 		snake_case	(			self ):
							return self.encoder_attention_heads






				@property
				def 		snake_case	(			self ):
							return self.d_model






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      copy.deepcopy(self.__dict__ )
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      self.backbone_config.to_dict()
							SCREAMING_SNAKE_CASE_   : Any					  =      self.__class__.model_type
							return output











# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
     import torch




class       snake_case__ (				TensorFormatter[Mapping, "torch.Tensor", Mapping]):

       '''simple docstring'''



       def __init__(				self      ,    a__=None      ,    **a__     )			->   Tuple:






            '''simple docstring'''





            super().__init__(features=a__     )
            __snake_case      :int 							=    torch_tensor_kwargs
            import torch  # noqa import torch at initialization



       def        __lowercase    (				self      ,    a__     )			->   List[str]:






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    a__     ) and column:
                 if all(
                     isinstance(a__      ,    torch.Tensor     ) and x.shape == column[0].shape and x.dtype == column[0].dtype
                     for x in column     ):
                      return torch.stack(a__     )
            return column



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






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    (str, bytes, type(a__     ))     ):
                 return value
            elif isinstance(a__      ,    (np.character, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.character     ):
                 return value.tolist()

            __snake_case      :Optional[int] 							=    {}

            if isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.integer     ):
                 __snake_case      :List[Any] 							=    {"""dtype""": torch.intaa}
            elif isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.floating     ):
                 __snake_case      :Tuple 							=    {"""dtype""": torch.floataa}
            elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(a__      ,    PIL.Image.Image     ):
                      __snake_case      :Union[str, Any] 							=    np.asarray(a__     )
            return torch.tensor(a__      ,    **{**default_dtype, **self.torch_tensor_kwargs}     )



       def        __lowercase    (				self      ,    a__     )			->   str:






            '''simple docstring'''





            import torch

            # support for torch, tf, jax etc.
            if hasattr(a__      ,    """__array__"""     ) and not isinstance(a__      ,    torch.Tensor     ):
                 __snake_case      :Optional[Any] 							=    data_struct.__array__()
            # support for nested types like struct of list of struct
            if isinstance(a__      ,    np.ndarray     ):
                 if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                      return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            elif isinstance(a__      ,    (list, tuple)     ):
                 return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            return self._tensorize(a__     )



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






            '''simple docstring'''





            return map_nested(self._recursive_tensorize      ,    a__      ,    map_list=a__     )



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.numpy_arrow_extractor().extract_row(a__     )
            __snake_case      :Any 							=    self.python_features_decoder.decode_row(a__     )
            return self.recursive_tensorize(a__     )



       def        __lowercase    (				self      ,    a__     )			->   "torch.Tensor":






            '''simple docstring'''





            __snake_case      :List[str] 							=    self.numpy_arrow_extractor().extract_column(a__     )
            __snake_case      :List[Any] 							=    self.python_features_decoder.decode_column(a__      ,    pa_table.column_names[0]     )
            __snake_case      :Optional[Any] 							=    self.recursive_tensorize(a__     )
            __snake_case      :Any 							=    self._consolidate(a__     )
            return column



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Optional[int] 							=    self.numpy_arrow_extractor().extract_batch(a__     )
            __snake_case      :Tuple 							=    self.python_features_decoder.decode_batch(a__     )
            __snake_case      :Tuple 							=    self.recursive_tensorize(a__     )
            for column_name in batch:
                 __snake_case      :str 							=    self._consolidate(batch[column_name]     )
            return batch


