
"""simple docstring"""




from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
    import timm


if is_torch_available():
    from torch import Tensor







class   _lowercase						(       __lowerCamelCase	,   __lowerCamelCase				):
     _A								=							'pixel_values'
     _A								=							False
     _A								=							TimmBackboneConfig



     def __init__(      self ,			__UpperCamelCase ,			**__UpperCamelCase  )->					Any:
          requires_backends(self ,			"timm"  )
          super().__init__(SCREAMING_SNAKE_CASE_  )
          UpperCAmelCase__							: Dict 							=						config

          if config.backbone is None:
               raise ValueError("backbone is not set in the config. Please set it to a timm model name."  )

          if config.backbone not in timm.list_models():
               raise ValueError(F"backbone {config.backbone} is not supported by timm."  )

          if hasattr(SCREAMING_SNAKE_CASE_ ,			"out_features"  ) and config.out_features is not None:
               raise ValueError("out_features is not supported by TimmBackbone. Please use out_indices instead."  )

          UpperCAmelCase__							: Dict 							=						getattr(SCREAMING_SNAKE_CASE_ ,			"use_pretrained_backbone" ,			SCREAMING_SNAKE_CASE_  )
          if pretrained is None:
               raise ValueError("use_pretrained_backbone is not set in the config. Please set it to True or False."  )

          # We just take the final layer by default. This matches the default for the transformers models.
          UpperCAmelCase__							: Dict 							=						config.out_indices if getattr(SCREAMING_SNAKE_CASE_ ,			"out_indices" ,			SCREAMING_SNAKE_CASE_  ) is not None else (-1,)

          UpperCAmelCase__							: str 							=						timm.create_model(
              config.backbone ,			pretrained=SCREAMING_SNAKE_CASE_ ,			features_only=config.features_only ,			in_chans=config.num_channels ,			out_indices=SCREAMING_SNAKE_CASE_ ,			**SCREAMING_SNAKE_CASE_ ,			)
          # These are used to control the output of the model when called. If output_hidden_states is True, then
          # return_layers is modified to include all layers.
          UpperCAmelCase__							: Union[str, Any] 							=						self._backbone.return_layers
          UpperCAmelCase__							: str 							=						{layer["module"]: str(SCREAMING_SNAKE_CASE_  ) for i, layer in enumerate(self._backbone.feature_info.info  )}
          super()._init_backbone(SCREAMING_SNAKE_CASE_  )



     @classmethod
     def  lowerCAmelCase__       (      cls ,			__UpperCamelCase ,			*__UpperCamelCase ,			**__UpperCamelCase  )->					List[str]:
          requires_backends(cls ,			["vision", "timm"]  )
          from ...models.timm_backbone import TimmBackboneConfig

          UpperCAmelCase__							: Union[str, Any] 							=						kwargs.pop("config" ,			TimmBackboneConfig()  )

          UpperCAmelCase__							: int 							=						kwargs.pop("use_timm_backbone" ,			SCREAMING_SNAKE_CASE_  )
          if not use_timm:
               raise ValueError("use_timm_backbone must be True for timm backbones"  )

          UpperCAmelCase__							: List[Any] 							=						kwargs.pop("num_channels" ,			config.num_channels  )
          UpperCAmelCase__							: Any 							=						kwargs.pop("features_only" ,			config.features_only  )
          UpperCAmelCase__							: str 							=						kwargs.pop("use_pretrained_backbone" ,			config.use_pretrained_backbone  )
          UpperCAmelCase__							: Union[str, Any] 							=						kwargs.pop("out_indices" ,			config.out_indices  )
          UpperCAmelCase__							: str 							=						TimmBackboneConfig(
              backbone=SCREAMING_SNAKE_CASE_ ,			num_channels=SCREAMING_SNAKE_CASE_ ,			features_only=SCREAMING_SNAKE_CASE_ ,			use_pretrained_backbone=SCREAMING_SNAKE_CASE_ ,			out_indices=SCREAMING_SNAKE_CASE_ ,			)
          return super()._from_config(SCREAMING_SNAKE_CASE_ ,			**SCREAMING_SNAKE_CASE_  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					str:
          pass



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=None ,			__UpperCamelCase=None ,			__UpperCamelCase=None ,			**__UpperCamelCase  )->					str:
          UpperCAmelCase__							: Optional[Any] 							=						return_dict if return_dict is not None else self.config.use_return_dict
          UpperCAmelCase__							: Union[str, Any] 							=						(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          UpperCAmelCase__							: Optional[Any] 							=						output_attentions if output_attentions is not None else self.config.output_attentions

          if output_attentions:
               raise ValueError("Cannot output attentions for timm backbones at the moment"  )

          if output_hidden_states:
               # We modify the return layers to include all the stages of the backbone
               UpperCAmelCase__							: str 							=						self._all_layers
               UpperCAmelCase__							: List[str] 							=						self._backbone(SCREAMING_SNAKE_CASE_ ,			**SCREAMING_SNAKE_CASE_  )
               UpperCAmelCase__							: Optional[Any] 							=						self._return_layers
               UpperCAmelCase__							: List[str] 							=						tuple(hidden_states[i] for i in self.out_indices  )
          else:
               UpperCAmelCase__							: List[Any] 							=						self._backbone(SCREAMING_SNAKE_CASE_ ,			**SCREAMING_SNAKE_CASE_  )
               UpperCAmelCase__							: List[str] 							=						None

          UpperCAmelCase__							: str 							=						tuple(SCREAMING_SNAKE_CASE_  )
          UpperCAmelCase__							: int 							=						tuple(SCREAMING_SNAKE_CASE_  ) if hidden_states is not None else None

          if not return_dict:
               UpperCAmelCase__							: List[Any] 							=						(feature_maps,)
               if output_hidden_states:
                    UpperCAmelCase__							: List[str] 							=						output + (hidden_states,)
               return output

          return BackboneOutput(feature_maps=SCREAMING_SNAKE_CASE_ ,			hidden_states=SCREAMING_SNAKE_CASE_ ,			attentions=SCREAMING_SNAKE_CASE_  )





"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from packaging import version

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


A__      :	Union[str, Any]          =    logging.get_logger(__name__)

A__      :	Optional[int]          =    {
    """microsoft/table-transformer-detection""": (
        """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"""
    ),
}







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							'table-transformer'
     _A								=							['past_key_values']
     _A								=							{
         'hidden_size': 'd_model',
         'num_attention_heads': 'encoder_attention_heads',
     }



     def __init__(      self ,			__UpperCamelCase=True ,			__UpperCamelCase=None ,			__UpperCamelCase=3 ,			__UpperCamelCase=1_00 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=True ,			__UpperCamelCase="relu" ,			__UpperCamelCase=2_56 ,			__UpperCamelCase=0.1 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.02 ,			__UpperCamelCase=1.0 ,			__UpperCamelCase=False ,			__UpperCamelCase="sine" ,			__UpperCamelCase="resnet50" ,			__UpperCamelCase=True ,			__UpperCamelCase=False ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=1 ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=0.1 ,			**__UpperCamelCase ,			)->					List[Any]:
          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__							: Any 							=						CONFIG_MAPPING["resnet"](out_features=["stage4"]  )
               elif isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
                    UpperCAmelCase__							: int 							=						backbone_config.get("model_type"  )
                    UpperCAmelCase__							: Optional[Any] 							=						CONFIG_MAPPING[backbone_model_type]
                    UpperCAmelCase__							: int 							=						config_class.from_dict(__UpperCamelCase  )
               # set timm attributes to None
               UpperCAmelCase__							,	UpperCAmelCase__							,	UpperCAmelCase__							: List[str] 							=						None, None, None

          UpperCAmelCase__							: Optional[int] 							=						use_timm_backbone
          UpperCAmelCase__							: Dict 							=						backbone_config
          UpperCAmelCase__							: List[Any] 							=						num_channels
          UpperCAmelCase__							: Any 							=						num_queries
          UpperCAmelCase__							: int 							=						d_model
          UpperCAmelCase__							: Optional[int] 							=						encoder_ffn_dim
          UpperCAmelCase__							: str 							=						encoder_layers
          UpperCAmelCase__							: Dict 							=						encoder_attention_heads
          UpperCAmelCase__							: Optional[Any] 							=						decoder_ffn_dim
          UpperCAmelCase__							: Tuple 							=						decoder_layers
          UpperCAmelCase__							: Optional[Any] 							=						decoder_attention_heads
          UpperCAmelCase__							: List[str] 							=						dropout
          UpperCAmelCase__							: Tuple 							=						attention_dropout
          UpperCAmelCase__							: List[Any] 							=						activation_dropout
          UpperCAmelCase__							: Dict 							=						activation_function
          UpperCAmelCase__							: Optional[Any] 							=						init_std
          UpperCAmelCase__							: List[str] 							=						init_xavier_std
          UpperCAmelCase__							: int 							=						encoder_layerdrop
          UpperCAmelCase__							: Tuple 							=						decoder_layerdrop
          UpperCAmelCase__							: int 							=						encoder_layers
          UpperCAmelCase__							: Dict 							=						auxiliary_loss
          UpperCAmelCase__							: Union[str, Any] 							=						position_embedding_type
          UpperCAmelCase__							: List[str] 							=						backbone
          UpperCAmelCase__							: List[Any] 							=						use_pretrained_backbone
          UpperCAmelCase__							: List[str] 							=						dilation
          # Hungarian matcher
          UpperCAmelCase__							: Dict 							=						class_cost
          UpperCAmelCase__							: Any 							=						bbox_cost
          UpperCAmelCase__							: Tuple 							=						giou_cost
          # Loss coefficients
          UpperCAmelCase__							: Any 							=						mask_loss_coefficient
          UpperCAmelCase__							: Dict 							=						dice_loss_coefficient
          UpperCAmelCase__							: Any 							=						bbox_loss_coefficient
          UpperCAmelCase__							: Tuple 							=						giou_loss_coefficient
          UpperCAmelCase__							: List[Any] 							=						eos_coefficient
          super().__init__(is_encoder_decoder=__UpperCamelCase ,			**__UpperCamelCase  )



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



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return self.d_model







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							version.parse('1.11'				)



     @property
     def  lowerCAmelCase__       (      self  )->					Mapping[str, Mapping[int, str]]:
          return OrderedDict(
              [
                  ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
                  ("pixel_mask", {0: "batch"}),
              ]  )



     @property
     def  lowerCAmelCase__       (      self  )->					float:
          return 1E-5



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return 12



