




'''simple docstring'''





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


_lowerCAmelCase										=     logging.get_logger(__name__)
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    lowerCAmelCase__			:  Dict											= r"\w+[.]\d+"
    lowerCAmelCase__			:  List[Any]											= re.findall(_SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE      )
    for pat in pats:
        lowerCAmelCase__			:  List[Any]											= key.replace(_SCREAMING_SNAKE_CASE							,   """_""".join(pat.split("""."""      )      )      )
    return key
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    lowerCAmelCase__			:  List[Any]											= 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)
    ):
        lowerCAmelCase__			:  Optional[int]											= 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:
        lowerCAmelCase__			:  Optional[int]											= 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:
        lowerCAmelCase__			:  List[Any]											= pt_tuple_key[:-1] + ("embedding",)
        return renamed_pt_tuple_key, pt_tensor

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

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

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

    # old PyTorch layer norm bias
    lowerCAmelCase__			:  Union[str, Any]											= 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        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase							,   UpperCamelCase=42      ):



    """simple docstring"""





    lowerCAmelCase__			:  Union[str, Any]											= {k: v.numpy() for k, v in pt_state_dict.items()}

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

    lowerCAmelCase__			:  Optional[int]											= flatten_dict(_SCREAMING_SNAKE_CASE      )
    lowerCAmelCase__			:  Optional[Any]											= {}

    # Need to change some parameters name to match Flax names
    for pt_key, pt_tensor in pt_state_dict.items():
        lowerCAmelCase__			:  str											= rename_key(_SCREAMING_SNAKE_CASE      )
        lowerCAmelCase__			:  int											= tuple(renamed_pt_key.split("""."""      )      )

        # Correctly rename weight parameters
        lowerCAmelCase__			:  int											= rename_key_and_reshape_tensor(_SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE      )

        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
        lowerCAmelCase__			:  Optional[int]											= jnp.asarray(_SCREAMING_SNAKE_CASE      )

    return unflatten_dict(_SCREAMING_SNAKE_CASE      )







'''simple docstring'''





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


_lowerCAmelCase										=     logging.get_logger(__name__)

_lowerCAmelCase										=     {
    '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''',
}






class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  __lowercase							:				Tuple           =				'''convnextv2'''




  def __init__(   self  ,__UpperCAmelCase=3  ,__UpperCAmelCase=4  ,__UpperCAmelCase=4  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=1E-12  ,__UpperCAmelCase=0.0  ,__UpperCAmelCase=224  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,**__UpperCAmelCase  ,)   ->		Union[str, Any]:
      super().__init__(**__UpperCAmelCase				)

      lowerCAmelCase__			:  int											= num_channels
      lowerCAmelCase__			:  List[Any]											= patch_size
      lowerCAmelCase__			:  Union[str, Any]											= num_stages
      lowerCAmelCase__			:  Tuple											= [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
      lowerCAmelCase__			:  str											= [3, 3, 9, 3] if depths is None else depths
      lowerCAmelCase__			:  Optional[Any]											= hidden_act
      lowerCAmelCase__			:  str											= initializer_range
      lowerCAmelCase__			:  List[str]											= layer_norm_eps
      lowerCAmelCase__			:  Dict											= drop_path_rate
      lowerCAmelCase__			:  int											= image_size
      lowerCAmelCase__			:  int											= ["""stem"""] + [F"""stage{idx}""" for idx in range(1  ,len(self.depths				) + 1				)]
      lowerCAmelCase__				,       lowerCAmelCase__			:  Tuple											= get_aligned_output_features_output_indices(
          out_features=__UpperCAmelCase  ,out_indices=__UpperCAmelCase  ,stage_names=self.stage_names				)


