"""simple docstring"""


from importlib import import_module

from .logging import get_logger


UpperCAmelCase__  		=						get_logger(__name__)


class        a				:


    def __init__(					self	:  int   ,				__lowerCAmelCase	:  Optional[int]   ,				__lowerCAmelCase	:  int=None					):
      _UpperCAmelCase						 =      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					)					)
      _UpperCAmelCase						 =      module._original_module if isinstance(__lowerCAmelCase   ,				_PatchedModuleObj					) else module



class        a				:
    _snake_case     :  List[str]     							=							[]


    def __init__(					self	:  Union[str, Any]   ,				__lowerCAmelCase	:  Any   ,				__lowerCAmelCase	:  str   ,				__lowerCAmelCase	:  Union[str, Any]   ,				__lowerCAmelCase	:  str=None					):
      _UpperCAmelCase						 =      obj
      _UpperCAmelCase						 =      target
      _UpperCAmelCase						 =      new
      _UpperCAmelCase						 =      target.split("""."""					)[0]
      _UpperCAmelCase						 =      {}
      _UpperCAmelCase						 =      attrs or []


    def __enter__(					self	:  str					):
      *_UpperCAmelCase ,				_UpperCAmelCase						 =      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:
          _UpperCAmelCase						 =      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__():
          _UpperCAmelCase						 =      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)
          ):
            _UpperCAmelCase						 =      obj_attr
            # patch at top level
            setattr(self.obj   ,				__lowerCAmelCase   ,				_PatchedModuleObj(__lowerCAmelCase   ,				attrs=self.attrs					)					)
            _UpperCAmelCase						 =      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					)					)
              _UpperCAmelCase						 =      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:
          _UpperCAmelCase						 =      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:
            _UpperCAmelCase						 =      getattr(self.obj   ,				__lowerCAmelCase					)
            setattr(self.obj   ,				__lowerCAmelCase   ,				self.new					)
      elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
        _UpperCAmelCase						 =      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	:  Optional[int]   ,				*__lowerCAmelCase	:  Dict					):
      for attr in list(self.original					):
        setattr(self.obj   ,				__lowerCAmelCase   ,				self.original.pop(__lowerCAmelCase					)					)


    def      lowerCAmelCase_  (					self	:  Dict					):
      self.__enter__()
      self._active_patches.append(self					)


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

      return self.__exit__()

"""simple docstring"""


from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


UpperCAmelCase__  		=						logging.get_logger(__name__)

UpperCAmelCase__  		=						{
    """shi-labs/nat-mini-in1k-224""": """https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json""",
    # See all Nat models at https://huggingface.co/models?filter=nat
}


class        a				(		lowerCAmelCase_	,							lowerCAmelCase_   ):
    _snake_case     :  Union[str, Any]     							=							'nat'

    _snake_case     :  List[str]     							=							{
        'num_attention_heads': 'num_heads',
        'num_hidden_layers': 'num_layers',
    }


    def __init__(					self	:  List[Any]   ,				__lowerCAmelCase	:  int=4   ,				__lowerCAmelCase	:  Union[str, Any]=3   ,				__lowerCAmelCase	:  Dict=64   ,				__lowerCAmelCase	:  int=[3, 4, 6, 5]   ,				__lowerCAmelCase	:  List[str]=[2, 4, 8, 16]   ,				__lowerCAmelCase	:  Tuple=7   ,				__lowerCAmelCase	:  List[str]=3.0   ,				__lowerCAmelCase	:  int=True   ,				__lowerCAmelCase	:  int=0.0   ,				__lowerCAmelCase	:  Tuple=0.0   ,				__lowerCAmelCase	:  Any=0.1   ,				__lowerCAmelCase	:  List[str]="gelu"   ,				__lowerCAmelCase	:  List[Any]=0.02   ,				__lowerCAmelCase	:  Union[str, Any]=1e-5   ,				__lowerCAmelCase	:  List[Any]=0.0   ,				__lowerCAmelCase	:  Tuple=None   ,				__lowerCAmelCase	:  Optional[int]=None   ,				**__lowerCAmelCase	:  Optional[Any]   ,				):
      super().__init__(**__lowerCAmelCase					)

      _UpperCAmelCase						 =      patch_size
      _UpperCAmelCase						 =      num_channels
      _UpperCAmelCase						 =      embed_dim
      _UpperCAmelCase						 =      depths
      _UpperCAmelCase						 =      len(__lowerCAmelCase					)
      _UpperCAmelCase						 =      num_heads
      _UpperCAmelCase						 =      kernel_size
      _UpperCAmelCase						 =      mlp_ratio
      _UpperCAmelCase						 =      qkv_bias
      _UpperCAmelCase						 =      hidden_dropout_prob
      _UpperCAmelCase						 =      attention_probs_dropout_prob
      _UpperCAmelCase						 =      drop_path_rate
      _UpperCAmelCase						 =      hidden_act
      _UpperCAmelCase						 =      layer_norm_eps
      _UpperCAmelCase						 =      initializer_range
      # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel
      # this indicates the channel dimension after the last stage of the model
      _UpperCAmelCase						 =      int(embed_dim * 2 ** (len(__lowerCAmelCase					) - 1)					)
      _UpperCAmelCase						 =      layer_scale_init_value
      _UpperCAmelCase						 =      ["""stem"""] + [f'''stage{idx}''' for idx in range(1   ,				len(__lowerCAmelCase					) + 1					)]
      _UpperCAmelCase ,				_UpperCAmelCase						 =      get_aligned_output_features_output_indices(
          out_features=__lowerCAmelCase   ,				out_indices=__lowerCAmelCase   ,				stage_names=self.stage_names					)
