

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


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

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







class        a__       (   __lowerCamelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Union[str, Any]			       ="""table-transformer"""
  UpperCAmelCase__      : Optional[int]			       =["""past_key_values"""]
  UpperCAmelCase__      : Union[str, Any]			       ={
      """hidden_size""": """d_model""",
      """num_attention_heads""": """encoder_attention_heads""",
  }


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

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


  @property
  def  _lowercase      (			self    : Union[str, Any]		)					->Optional[Any]:
        """simple docstring"""







        return self.encoder_attention_heads




  @property
  def  _lowercase      (			self    : Optional[Any]		)					->str:
        """simple docstring"""







        return self.d_model







class        a__       (   __lowerCamelCase       ):







  """simple docstring"""




  UpperCAmelCase__      : Tuple			       =version.parse("""1.11"""       )


  @property
  def  _lowercase      (			self    : Optional[Any]		)					->List[str]:
        """simple docstring"""







        return OrderedDict(
            [
                ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
                ("""pixel_mask""", {0: """batch"""}),
            ]		)


  @property
  def  _lowercase      (			self    : Optional[int]		)					->Optional[Any]:
        """simple docstring"""







        return 1e-5




  @property
  def  _lowercase      (			self    : List[Any]		)					->Dict:
        """simple docstring"""







        return 1_2







import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Tuple		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   []
        SCREAMING_SNAKE_CASE :      Any       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      List[Any]       =   self.in_channels if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxResnetBlockaD(
                  in_channels=UpperCAmelCase__				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      List[Any]       =   FlaxTransformeraDModel(
                  in_channels=self.out_channels				,				n_heads=self.num_attention_heads				,				d_head=self.out_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				only_cross_attention=self.only_cross_attention				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   resnets
        SCREAMING_SNAKE_CASE :      Optional[int]       =   attentions

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxDownsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : int				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Optional[Any]				,				UpperCAmelCase__    : List[str]=True		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   ()

        for resnet, attn in zip(self.resnets				,				self.attentions		):
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      List[str]       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              output_states += (hidden_states,)

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      int       =   self.downsamplers_a(UpperCAmelCase__		)
              output_states += (hidden_states,)

        return hidden_states, output_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Dict		)					->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.in_channels if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxResnetBlockaD(
                  in_channels=UpperCAmelCase__				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   resnets

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      List[str]       =   FlaxDownsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Tuple				,				UpperCAmelCase__    : int				,				UpperCAmelCase__    : Optional[Any]				,				UpperCAmelCase__    : Any=True		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   ()

        for resnet in self.resnets:
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              output_states += (hidden_states,)

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      Dict       =   self.downsamplers_a(UpperCAmelCase__		)
              output_states += (hidden_states,)

        return hidden_states, output_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : int		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   []
        SCREAMING_SNAKE_CASE :      List[Any]       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Any       =   self.in_channels if (i == self.num_layers - 1) else self.out_channels
              SCREAMING_SNAKE_CASE :      Any       =   self.prev_output_channel if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxResnetBlockaD(
                  in_channels=resnet_in_channels + res_skip_channels				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxTransformeraDModel(
                  in_channels=self.out_channels				,				n_heads=self.num_attention_heads				,				d_head=self.out_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				only_cross_attention=self.only_cross_attention				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   resnets
        SCREAMING_SNAKE_CASE :      List[Any]       =   attentions

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxUpsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Union[str, Any]				,				UpperCAmelCase__    : str				,				UpperCAmelCase__    : List[Any]				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Dict=True		)					->Tuple:
        """simple docstring"""







        for resnet, attn in zip(self.resnets				,				self.attentions		):
              # pop res hidden states
              SCREAMING_SNAKE_CASE :      str       =   res_hidden_states_tuple[-1]
              SCREAMING_SNAKE_CASE :      Dict       =   res_hidden_states_tuple[:-1]
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   jnp.concatenate((hidden_states, res_hidden_states)				,				axis=-1		)

              SCREAMING_SNAKE_CASE :      Tuple       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Tuple       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Tuple       =   self.upsamplers_a(UpperCAmelCase__		)

        return hidden_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Union[str, Any]		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[Any]       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.in_channels if (i == self.num_layers - 1) else self.out_channels
              SCREAMING_SNAKE_CASE :      str       =   self.prev_output_channel if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Optional[int]       =   FlaxResnetBlockaD(
                  in_channels=resnet_in_channels + res_skip_channels				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Dict       =   resnets

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      int       =   FlaxUpsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Optional[Any]				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Dict				,				UpperCAmelCase__    : Tuple				,				UpperCAmelCase__    : Optional[int]=True		)					->Union[str, Any]:
        """simple docstring"""







        for resnet in self.resnets:
              # pop res hidden states
              SCREAMING_SNAKE_CASE :      Dict       =   res_hidden_states_tuple[-1]
              SCREAMING_SNAKE_CASE :      Any       =   res_hidden_states_tuple[:-1]
              SCREAMING_SNAKE_CASE :      Tuple       =   jnp.concatenate((hidden_states, res_hidden_states)				,				axis=-1		)

              SCREAMING_SNAKE_CASE :      Optional[int]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   self.upsamplers_a(UpperCAmelCase__		)

        return hidden_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Optional[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   [
            FlaxResnetBlockaD(
                in_channels=self.in_channels				,				out_channels=self.in_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
        ]

        SCREAMING_SNAKE_CASE :      List[str]       =   []

        for _ in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxTransformeraDModel(
                  in_channels=self.in_channels				,				n_heads=self.num_attention_heads				,				d_head=self.in_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      List[str]       =   FlaxResnetBlockaD(
                  in_channels=self.in_channels				,				out_channels=self.in_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   resnets
        SCREAMING_SNAKE_CASE :      Tuple       =   attentions




  def __call__(			self    : Union[str, Any]				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : str=True		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   self.resnets[0](UpperCAmelCase__				,				UpperCAmelCase__		)
        for attn, resnet in zip(self.attentions				,				self.resnets[1:]		):
              SCREAMING_SNAKE_CASE :      Optional[int]       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        return hidden_states




