



from importlib import import_module

from .logging import get_logger


SCREAMING_SNAKE_CASE_:Optional[Any]					=						get_logger(__name__)






class SCREAMING_SNAKE_CASE__					:




    '''simple docstring'''






    def __init__(	self,		lowerCamelCase__,		lowerCamelCase__=None		):
        A			:	Optional[int]										=       attrs or []
        if module is not None:
            for key in module.__dict__:
                if key in attrs or not key.startswith("""__"""		):
                    setattr(self,		lowerCamelCase__,		getattr(lowerCamelCase__,		lowerCamelCase__		)		)
        A			:	Union[str, Any]										=       module._original_module if isinstance(lowerCamelCase__,		_PatchedModuleObj		) else module






class SCREAMING_SNAKE_CASE__					:




    '''simple docstring'''






    __lowerCamelCase      :			List[Any] =				[]






    def __init__(	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__=None		):
        A			:	Optional[int]										=       obj
        A			:	List[Any]										=       target
        A			:	List[Any]										=       new
        A			:	Tuple										=       target.split("""."""		)[0]
        A			:	Any										=       {}
        A			:	Optional[Any]										=       attrs or []






    def __enter__(	self		):
        *A					,							A			:	Optional[int]										=       self.target.split("""."""		)

        # Patch modules:
        # it's used to patch attributes of submodules like "os.path.join";
        # in this case we need to patch "os" and "os.path"

        for i in range(len(lowerCamelCase__		)		):
            try:
                A			:	Dict										=       import_module(""".""".join(submodules[: i + 1]		)		)
            except ModuleNotFoundError:
                continue
            # We iterate over all the globals in self.obj in case we find "os" or "os.path"
            for attr in self.obj.__dir__():
                A			:	Optional[int]										=       getattr(self.obj,		lowerCamelCase__		)
                # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                # This allows to patch renamed modules like "from os import path as ospath".
                if obj_attr is submodule or (
                    (isinstance(lowerCamelCase__,		_PatchedModuleObj		) and obj_attr._original_module is submodule)
                ):
                    A			:	List[str]										=       obj_attr
                    # patch at top level
                    setattr(self.obj,		lowerCamelCase__,		_PatchedModuleObj(lowerCamelCase__,		attrs=self.attrs		)		)
                    A			:	Any										=       getattr(self.obj,		lowerCamelCase__		)
                    # construct lower levels patches
                    for key in submodules[i + 1 :]:
                        setattr(lowerCamelCase__,		lowerCamelCase__,		_PatchedModuleObj(getattr(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		),		attrs=self.attrs		)		)
                        A			:	Optional[Any]										=       getattr(lowerCamelCase__,		lowerCamelCase__		)
                    # finally set the target attribute
                    setattr(lowerCamelCase__,		lowerCamelCase__,		self.new		)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

        if submodules:  # if it's an attribute of a submodule like "os.path.join"
            try:
                A			:	Union[str, Any]										=       getattr(import_module(""".""".join(lowerCamelCase__		)		),		lowerCamelCase__		)
            except (AttributeError, ModuleNotFoundError):
                return
            # We iterate over all the globals in self.obj in case we find "os.path.join"
            for attr in self.obj.__dir__():
                # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                # This allows to patch renamed attributes like "from os.path import join as pjoin".
                if getattr(self.obj,		lowerCamelCase__		) is attr_value:
                    A			:	Dict										=       getattr(self.obj,		lowerCamelCase__		)
                    setattr(self.obj,		lowerCamelCase__,		self.new		)
        elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
            A			:	Dict										=       globals()["""__builtins__"""][target_attr]
            setattr(self.obj,		lowerCamelCase__,		self.new		)
        else:
            raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''		)






    def __exit__(	self,		*lowerCamelCase__		):
        for attr in list(self.original		):
            setattr(self.obj,		lowerCamelCase__,		self.original.pop(lowerCamelCase__		)		)






    def       _lowerCAmelCase (	self		):
        self.__enter__()
        self._active_patches.append(self		)






    def       _lowerCAmelCase (	self		):
        try:
            self._active_patches.remove(self		)
        except ValueError:
            # If the patch hasn't been started this will fail
            return None

        return self.__exit__()







import copy
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


SCREAMING_SNAKE_CASE_:Optional[Any]					=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_:Union[str, Any]					=						{
    """microsoft/conditional-detr-resnet-50""": (
        """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json"""
    ),
}






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			Dict =				"conditional_detr"
    __lowerCamelCase      :			str =				["past_key_values"]
    __lowerCamelCase      :			str =				{
        "hidden_size": "d_model",
        "num_attention_heads": "encoder_attention_heads",
    }






    def __init__(	self,		lowerCamelCase__=True,		lowerCamelCase__=None,		lowerCamelCase__=3,		lowerCamelCase__=300,		lowerCamelCase__=6,		lowerCamelCase__=2048,		lowerCamelCase__=8,		lowerCamelCase__=6,		lowerCamelCase__=2048,		lowerCamelCase__=8,		lowerCamelCase__=0.0,		lowerCamelCase__=0.0,		lowerCamelCase__=True,		lowerCamelCase__="relu",		lowerCamelCase__=256,		lowerCamelCase__=0.1,		lowerCamelCase__=0.0,		lowerCamelCase__=0.0,		lowerCamelCase__=0.02,		lowerCamelCase__=1.0,		lowerCamelCase__=False,		lowerCamelCase__="sine",		lowerCamelCase__="resnet50",		lowerCamelCase__=True,		lowerCamelCase__=False,		lowerCamelCase__=2,		lowerCamelCase__=5,		lowerCamelCase__=2,		lowerCamelCase__=1,		lowerCamelCase__=1,		lowerCamelCase__=2,		lowerCamelCase__=5,		lowerCamelCase__=2,		lowerCamelCase__=0.25,		**lowerCamelCase__,		):
        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."""		)
                A			:	List[Any]										=       CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]		)
            elif isinstance(lowerCamelCase__,		lowerCamelCase__		):
                A			:	Any										=       backbone_config.get("""model_type"""		)
                A			:	Optional[Any]										=       CONFIG_MAPPING[backbone_model_type]
                A			:	Tuple										=       config_class.from_dict(lowerCamelCase__		)

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






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






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






    def       _lowerCAmelCase (	self		):
        A			:	Dict										=       copy.deepcopy(self.__dict__		)
        if self.backbone_config is not None:
            A			:	List[Any]										=       self.backbone_config.to_dict()
        A			:	List[str]										=       self.__class__.model_type
        return output






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






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






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






    @property
    def       _lowerCAmelCase (	self		):
        return 1e-5






    @property
    def       _lowerCAmelCase (	self		):
        return 12


