



import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
       from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
       import torch_xla.core.xla_model as xm

def   _lowerCAmelCase   (						A__	):
      if is_torch_version('<'						,  '2.0.0'	) or not hasattr(A__						,  '_dynamo'	):
            return False
      return isinstance(A__						,  torch._dynamo.eval_frame.OptimizedModule	)

def   _lowerCAmelCase   (						A__						,  A__ = True	):
      lowercase__     =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

      lowercase__     =  is_compiled_module(A__	)
      if is_compiled:
            lowercase__     =  model
            lowercase__     =  model._orig_mod

      if is_deepspeed_available():
            options += (DeepSpeedEngine,)

      while isinstance(A__						,  A__	):
            lowercase__     =  model.module

      if not keep_fpaa_wrapper:
            lowercase__     =  getattr(A__						,  'forward'	)
            lowercase__     =  model.__dict__.pop('_original_forward'						,  A__	)
            if original_forward is not None:
                  while hasattr(A__						,  '__wrapped__'	):
                        lowercase__     =  forward.__wrapped__
                        if forward == original_forward:
                              break
                  lowercase__     =  forward
            if getattr(A__						,  '_converted_to_transformer_engine'						,  A__	):
                  convert_model(A__						,  to_transformer_engine=A__	)

      if is_compiled:
            lowercase__     =  model
            lowercase__     =  compiled_model

      return model

def   _lowerCAmelCase   (						):
      PartialState().wait_for_everyone()

def   _lowerCAmelCase   (						A__						,  A__	):
      if PartialState().distributed_type == DistributedType.TPU:
            xm.save(A__						,  A__	)
      elif PartialState().local_process_index == 0:
            torch.save(A__						,  A__	)

@contextmanager
def   _lowerCAmelCase   (						**A__	):
      for key, value in kwargs.items():
            lowercase__     =  str(A__	)

      yield

      for key in kwargs:
            if key.upper() in os.environ:
                  del os.environ[key.upper()]

def   _lowerCAmelCase   (						A__	):
      if not hasattr(A__						,  '__qualname__'	) and not hasattr(A__						,  '__name__'	):
            lowercase__     =  getattr(A__						,  '__class__'						,  A__	)
      if hasattr(A__						,  '__qualname__'	):
            return obj.__qualname__
      if hasattr(A__						,  '__name__'	):
            return obj.__name__
      return str(A__	)

def   _lowerCAmelCase   (						A__						,  A__	):
      for key, value in source.items():
            if isinstance(A__						,  A__	):
                  lowercase__     =  destination.setdefault(A__						,  {}	)
                  merge_dicts(A__						,  A__	)
            else:
                  lowercase__     =  value

      return destination

def   _lowerCAmelCase   (						A__ = None	):
      if port is None:
            lowercase__     =  29_500
      with socket.socket(socket.AF_INET						,  socket.SOCK_STREAM	) as s:
            return s.connect_ex(('localhost', port)	) == 0





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


a__      :				List[str]   	=			logging.get_logger(__name__)

a__      :				List[Any]   	=			{
    "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json",
}



class       UpperCAmelCase__(							lowerCamelCase     ,							lowerCamelCase	):

   '''simple docstring'''




   A    :  List[str]       				=    "focalnet"


   def __init__(						self  :			Dict			,				lowerCAmelCase  :			Union[str, Any]=2_24			,				lowerCAmelCase  :			List[str]=4			,				lowerCAmelCase  :			int=3			,				lowerCAmelCase  :			Union[str, Any]=96			,				lowerCAmelCase  :			List[Any]=False			,				lowerCAmelCase  :			int=[1_92, 3_84, 7_68, 7_68]			,				lowerCAmelCase  :			str=[2, 2, 6, 2]			,				lowerCAmelCase  :			Tuple=[2, 2, 2, 2]			,				lowerCAmelCase  :			Optional[Any]=[3, 3, 3, 3]			,				lowerCAmelCase  :			int="gelu"			,				lowerCAmelCase  :			Any=4.0			,				lowerCAmelCase  :			List[str]=0.0			,				lowerCAmelCase  :			Union[str, Any]=0.1			,				lowerCAmelCase  :			Union[str, Any]=False			,				lowerCAmelCase  :			Tuple=1E-4			,				lowerCAmelCase  :			List[Any]=False			,				lowerCAmelCase  :			Optional[int]=False			,				lowerCAmelCase  :			List[str]=False			,				lowerCAmelCase  :			str=0.02			,				lowerCAmelCase  :			Optional[int]=1E-5			,				lowerCAmelCase  :			List[Any]=32			,				lowerCAmelCase  :			List[Any]=None			,				lowerCAmelCase  :			Union[str, Any]=None			,				**lowerCAmelCase  :			str			,				)	->				List[str]:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)

         lowercase__     =  image_size
         lowercase__     =  patch_size
         lowercase__     =  num_channels
         lowercase__     =  embed_dim
         lowercase__     =  use_conv_embed
         lowercase__     =  hidden_sizes
         lowercase__     =  depths
         lowercase__     =  focal_levels
         lowercase__     =  focal_windows
         lowercase__     =  hidden_act
         lowercase__     =  mlp_ratio
         lowercase__     =  hidden_dropout_prob
         lowercase__     =  drop_path_rate
         lowercase__     =  use_layerscale
         lowercase__     =  layerscale_value
         lowercase__     =  use_post_layernorm
         lowercase__     =  use_post_layernorm_in_modulation
         lowercase__     =  normalize_modulator
         lowercase__     =  initializer_range
         lowercase__     =  layer_norm_eps
         lowercase__     =  encoder_stride
         lowercase__     =  ['stem'] + [f'''stage{idx}''' for idx in range(1			,				len(self.depths) + 1)]
         lowercase__,	lowercase__     =  get_aligned_output_features_output_indices(
             out_features=lowerCAmelCase			,				out_indices=lowerCAmelCase			,				stage_names=self.stage_names)
