



import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


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

def   _lowerCAmelCase   (						A__	):
      lowercase__     =  r"""\w+[.]\d+"""
      lowercase__     =  re.findall(A__						,  A__	)
      for pat in pats:
            lowercase__     =  key.replace(A__						,  '_'.join(pat.split('.'	)	)	)
      return key

def   _lowerCAmelCase   (						A__						,  A__						,  A__	):
      lowercase__     =  pt_tuple_key[:-1] + ("""scale""",)
      if (
          any('norm' in str_ for str_ in pt_tuple_key	)
          and (pt_tuple_key[-1] == "bias")
          and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
          and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
      ):
            lowercase__     =  pt_tuple_key[:-1] + ("""scale""",)
            return renamed_pt_tuple_key, pt_tensor
      elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
            lowercase__     =  pt_tuple_key[:-1] + ("""scale""",)
            return renamed_pt_tuple_key, pt_tensor

      # embedding
      if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
            lowercase__     =  pt_tuple_key[:-1] + ("""embedding""",)
            return renamed_pt_tuple_key, pt_tensor

      # conv layer
      lowercase__     =  pt_tuple_key[:-1] + ("""kernel""",)
      if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
            lowercase__     =  pt_tensor.transpose(2						,  3						,  1						,  0	)
            return renamed_pt_tuple_key, pt_tensor

      # linear layer
      lowercase__     =  pt_tuple_key[:-1] + ("""kernel""",)
      if pt_tuple_key[-1] == "weight":
            lowercase__     =  pt_tensor.T
            return renamed_pt_tuple_key, pt_tensor

      # old PyTorch layer norm weight
      lowercase__     =  pt_tuple_key[:-1] + ("""weight""",)
      if pt_tuple_key[-1] == "gamma":
            return renamed_pt_tuple_key, pt_tensor

      # old PyTorch layer norm bias
      lowercase__     =  pt_tuple_key[:-1] + ("""bias""",)
      if pt_tuple_key[-1] == "beta":
            return renamed_pt_tuple_key, pt_tensor

      return pt_tuple_key, pt_tensor

def   _lowerCAmelCase   (						A__						,  A__						,  A__=42	):
      # Step 1: Convert pytorch tensor to numpy
      lowercase__     =  {k: v.numpy() for k, v in pt_state_dict.items()}

      # Step 2: Since the model is stateless, get random Flax params
      lowercase__     =  flax_model.init_weights(PRNGKey(A__	)	)

      lowercase__     =  flatten_dict(A__	)
      lowercase__     =  {}

      # Need to change some parameters name to match Flax names
      for pt_key, pt_tensor in pt_state_dict.items():
            lowercase__     =  rename_key(A__	)
            lowercase__     =  tuple(renamed_pt_key.split('.'	)	)

            # Correctly rename weight parameters
            lowercase__     =  rename_key_and_reshape_tensor(A__						,  A__						,  A__	)

            if flax_key in random_flax_state_dict:
                  if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
                        raise ValueError(
                            F'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '''
                            F'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.'''	)

        # also add unexpected weight so that warning is thrown
            lowercase__     =  jnp.asarray(A__	)

      return unflatten_dict(A__	)





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)
