'''simple docstring'''




import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel

def      UpperCamelCase_							( _UpperCAmelCase  :				Dict      ,     _UpperCAmelCase  :				Tuple      ,     _UpperCAmelCase  :				str   )   ->   Union[str, Any]:


       """simple docstring"""







       _UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase					:  Tuple											=   pt_weights[F"""{prefix}.in_proj_weight"""].chunk(3      ,     dim=0   )
       _UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase					:  Dict											=   pt_weights[F"""{prefix}.in_proj_bias"""].chunk(3      ,     dim=0   )

       _UpperCAmelCase					:  Tuple											=   pt_weights[F"""{prefix}.out_proj.weight"""]
       _UpperCAmelCase					:  Any											=   pt_weights[F"""{prefix}.out_proj.bias"""]

       _UpperCAmelCase					:  int											=   q_proj
       _UpperCAmelCase					:  Optional[int]											=   q_proj_bias

       _UpperCAmelCase					:  Any											=   k_proj
       _UpperCAmelCase					:  Tuple											=   k_proj_bias

       _UpperCAmelCase					:  str											=   v_proj
       _UpperCAmelCase					:  Union[str, Any]											=   v_proj_bias

       _UpperCAmelCase					:  Dict											=   out_proj_weights
       _UpperCAmelCase					:  List[Any]											=   out_proj_bias

def      UpperCamelCase_							( _UpperCAmelCase  :				List[str]      ,     _UpperCAmelCase  :				Tuple      ,     _UpperCAmelCase  :				Optional[Any]   )   ->   Union[str, Any]:


       """simple docstring"""







       copy_linear(hf_mlp.fca      ,     _UpperCAmelCase      ,     F"""{prefix}.c_fc"""   )
       copy_linear(hf_mlp.fca      ,     _UpperCAmelCase      ,     F"""{prefix}.c_proj"""   )

def      UpperCamelCase_							( _UpperCAmelCase  :				Optional[Any]      ,     _UpperCAmelCase  :				List[str]      ,     _UpperCAmelCase  :				str   )   ->   int:


       """simple docstring"""







       _UpperCAmelCase					:  Tuple											=   pt_weights[F"""{prefix}.weight"""].data
       _UpperCAmelCase					:  Dict											=   pt_weights[F"""{prefix}.bias"""].data

def      UpperCamelCase_							( _UpperCAmelCase  :				Union[str, Any]      ,     _UpperCAmelCase  :				List[Any]      ,     _UpperCAmelCase  :				List[str]   )   ->   Any:


       """simple docstring"""







       copy_linear(hf_layer.layer_norma      ,     _UpperCAmelCase      ,     F"""{prefix}.ln_1"""   )
       copy_linear(hf_layer.layer_norma      ,     _UpperCAmelCase      ,     F"""{prefix}.ln_2"""   )

       # copy MLP
       copy_mlp(hf_layer.mlp      ,     _UpperCAmelCase      ,     F"""{prefix}.mlp"""   )

       # copy attn
       copy_attn_layer(hf_layer.self_attn      ,     _UpperCAmelCase      ,     F"""{prefix}.attn"""   )

def      UpperCamelCase_							( _UpperCAmelCase  :				List[Any]      ,     _UpperCAmelCase  :				Union[str, Any]      ,     _UpperCAmelCase  :				List[str]   )   ->   Any:


       """simple docstring"""







       for layer_id, hf_layer in enumerate(_UpperCAmelCase   ):
              copy_layer(_UpperCAmelCase      ,     _UpperCAmelCase      ,     F"""{prefix}.{layer_id}"""   )

def      UpperCamelCase_							( _UpperCAmelCase  :				List[str]      ,     _UpperCAmelCase  :				Optional[Any]   )   ->   Dict:


       """simple docstring"""







       _UpperCAmelCase					:  Any											=   pt_weights["text_projection"].data.T

       # copy text encoder
       for name, param in hf_model.text_model.named_parameters():
              _UpperCAmelCase					:  Union[str, Any]											=   pt_weights[F"""bert.{name}"""].data

def      UpperCamelCase_							( _UpperCAmelCase  :				Tuple      ,     _UpperCAmelCase  :				Tuple   )   ->   int:


       """simple docstring"""







       _UpperCAmelCase					:  Optional[int]											=   pt_weights["visual.proj"].data.T

       # copy layer norms
       copy_linear(hf_model.vision_model.pre_layrnorm      ,     _UpperCAmelCase      ,     "visual.ln_pre"   )
       copy_linear(hf_model.vision_model.post_layernorm      ,     _UpperCAmelCase      ,     "visual.ln_post"   )

       # copy embeddings
       _UpperCAmelCase					:  str											=   pt_weights["visual.conv1.weight"].data
       _UpperCAmelCase					:  Dict											=   pt_weights["visual.class_embedding"].data
       _UpperCAmelCase					:  Optional[int]											=   pt_weights["visual.positional_embedding"].data

       # copy encoder
       copy_layers(hf_model.vision_model.encoder.layers      ,     _UpperCAmelCase      ,     "visual.transformer.resblocks"   )

@torch.no_grad()
def      UpperCamelCase_							( _UpperCAmelCase  :				Union[str, Any]      ,     _UpperCAmelCase  :				Optional[int]      ,     _UpperCAmelCase  :				Union[str, Any]=None   )   ->   Dict:


       """simple docstring"""







       assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
       _UpperCAmelCase					:  Dict											=   ChineseCLIPConfig.from_pretrained(_UpperCAmelCase   )

       _UpperCAmelCase					:  List[str]											=   ChineseCLIPModel(_UpperCAmelCase   ).eval()

       _UpperCAmelCase					:  str											=   torch.load(_UpperCAmelCase      ,     map_location="cpu"   )["state_dict"]
       _UpperCAmelCase					:  Optional[int]											=   {(name[7:] if name.startswith("module."   ) else name): value for name, value in pt_weights.items()}

       copy_text_model_and_projection(_UpperCAmelCase      ,     _UpperCAmelCase   )
       copy_vision_model_and_projection(_UpperCAmelCase      ,     _UpperCAmelCase   )
       _UpperCAmelCase					:  Union[str, Any]											=   pt_weights["logit_scale"].data

       hf_model.save_pretrained(_UpperCAmelCase   )


if __name__ == "__main__":
  __SCREAMING_SNAKE_CASE	:					Dict					=  argparse.ArgumentParser()
  parser.add_argument(
      """--pytorch_dump_folder_path""",
      default=None,
      type=str,
      help="""Path to the output folder storing converted hf PyTorch model.""",
  )
  parser.add_argument(
      """--checkpoint_path""", default=None, type=str, help="""Path to original github format ChineseCLIP checkpoint."""
  )
  parser.add_argument(
      """--config_path""", default=None, required=True, type=str, help="""Path to hf config.json of model to convert."""
  )
  __SCREAMING_SNAKE_CASE	:					int					=  parser.parse_args()

  convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
  print("""The conversion is finished!""")


'''simple docstring'''




import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter

class      lowerCamelCase_     (TensorFormatter[Mapping, np.ndarray, Mapping]   ):
      '''simple docstring'''

      def __init__(	self						:    str						, A						:    List[str]=None						, **A						:    Optional[Any]	):
             super().__init__(features=A	)
             _UpperCAmelCase					:  Tuple											=   np_array_kwargs




      def 					_A     (	self						:    str						, A						:    Tuple	):
             if isinstance(A						, A	):
                    if column and all(
                        isinstance(A						, np.ndarray	) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column	):
                           return np.stack(A	)
                    else:
                           # don't use np.array(column, dtype=object)
                           # since it fails in certain cases
                           # see https://stackoverflow.com/q/51005699
                           _UpperCAmelCase					:  List[str]											=   np.empty(len(A	)						, dtype=A	)
                           _UpperCAmelCase					:  int											=   column
                           return out
             return column




      def 					_A     (	self						:    Any						, A						:    Optional[Any]	):
             if isinstance(A						, (str, bytes, type(A	))	):
                    return value
             elif isinstance(A						, (np.character, np.ndarray)	) and np.issubdtype(value.dtype						, np.character	):
                    return value
             elif isinstance(A						, np.number	):
                    return value

             _UpperCAmelCase					:  List[str]											=   {}

             if isinstance(A						, np.ndarray	) and np.issubdtype(value.dtype						, np.integer	):
                    _UpperCAmelCase					:  str											=   {"dtype": np.intaa}
             elif isinstance(A						, np.ndarray	) and np.issubdtype(value.dtype						, np.floating	):
                    _UpperCAmelCase					:  int											=   {"dtype": np.floataa}
             elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                    import PIL.Image

                    if isinstance(A						, PIL.Image.Image	):
                           return np.asarray(A						, **self.np_array_kwargs	)

             return np.asarray(A						, **{**default_dtype, **self.np_array_kwargs}	)




      def 					_A     (	self						:    Any						, A						:    Optional[Any]	):
             # support for torch, tf, jax etc.
             if config.TORCH_AVAILABLE and "torch" in sys.modules:
                    import torch

                    if isinstance(A						, torch.Tensor	):
                           return self._tensorize(data_struct.detach().cpu().numpy()[()]	)
             if hasattr(A						, "__array__"	) and not isinstance(A						, (np.ndarray, np.character, np.number)	):
                    _UpperCAmelCase					:  Dict											=   data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(A						, np.ndarray	):
                    if data_struct.dtype == object:
                           return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
             if isinstance(A						, (list, tuple)	):
                    return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
             return self._tensorize(A	)




      def 					_A     (	self						:    List[Any]						, A						:    dict	):
             return map_nested(self._recursive_tensorize						, A						, map_list=A	)




      def 					_A     (	self						:    List[str]						, A						:    pa.Table	):
             _UpperCAmelCase					:  str											=   self.numpy_arrow_extractor().extract_row(A	)
             _UpperCAmelCase					:  Dict											=   self.python_features_decoder.decode_row(A	)
             return self.recursive_tensorize(A	)




      def 					_A     (	self						:    str						, A						:    pa.Table	):
             _UpperCAmelCase					:  List[str]											=   self.numpy_arrow_extractor().extract_column(A	)
             _UpperCAmelCase					:  Optional[Any]											=   self.python_features_decoder.decode_column(A						, pa_table.column_names[0]	)
             _UpperCAmelCase					:  Tuple											=   self.recursive_tensorize(A	)
             _UpperCAmelCase					:  Tuple											=   self._consolidate(A	)
             return column





      def 					_A     (	self						:    Union[str, Any]						, A						:    pa.Table	):
             _UpperCAmelCase					:  Any											=   self.numpy_arrow_extractor().extract_batch(A	)
             _UpperCAmelCase					:  Any											=   self.python_features_decoder.decode_batch(A	)
             _UpperCAmelCase					:  List[str]											=   self.recursive_tensorize(A	)
             for column_name in batch:
                    _UpperCAmelCase					:  Optional[Any]											=   self._consolidate(batch[column_name]	)
             return batch

