


import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel

def       _a	(					SCREAMING_SNAKE_CASE						:					List[str]     ,			SCREAMING_SNAKE_CASE						:					Optional[int]     ,			SCREAMING_SNAKE_CASE						:					Optional[Any]  ):







 """simple docstring"""



 UpperCamelCase__       :     List[Any] 							= pt_weights[F"{prefix}.in_proj_weight"].chunk(3     ,			dim=0  )
 UpperCamelCase__       :     Optional[Any] 							= 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__       :     Optional[int] 							= q_proj
 UpperCamelCase__       :     Dict 							= q_proj_bias

 UpperCamelCase__       :     List[Any] 							= k_proj
 UpperCamelCase__       :     Optional[int] 							= k_proj_bias

 UpperCamelCase__       :     Union[str, Any] 							= v_proj
 UpperCamelCase__       :     Optional[Any] 							= v_proj_bias

 UpperCamelCase__       :     Union[str, Any] 							= out_proj_weights
 UpperCamelCase__       :     Optional[int] 							= out_proj_bias

def       _a	(					SCREAMING_SNAKE_CASE						:					Dict     ,			SCREAMING_SNAKE_CASE						:					Optional[int]     ,			SCREAMING_SNAKE_CASE						:					Tuple  ):







 """simple docstring"""



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

def       _a	(					SCREAMING_SNAKE_CASE						:					Optional[Any]     ,			SCREAMING_SNAKE_CASE						:					List[Any]     ,			SCREAMING_SNAKE_CASE						:					Optional[int]  ):







 """simple docstring"""



 UpperCamelCase__       :     List[Any] 							= pt_weights[F"{prefix}.weight"].data
 UpperCamelCase__       :     Union[str, Any] 							= pt_weights[F"{prefix}.bias"].data

def       _a	(					SCREAMING_SNAKE_CASE						:					Union[str, Any]     ,			SCREAMING_SNAKE_CASE						:					Union[str, Any]     ,			SCREAMING_SNAKE_CASE						:					Optional[Any]  ):







 """simple docstring"""



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

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

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

def       _a	(					SCREAMING_SNAKE_CASE						:					Any     ,			SCREAMING_SNAKE_CASE						:					Union[str, Any]     ,			SCREAMING_SNAKE_CASE						:					Union[str, Any]  ):







 """simple docstring"""



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

def       _a	(					SCREAMING_SNAKE_CASE						:					Tuple     ,			SCREAMING_SNAKE_CASE						:					Optional[int]  ):







 """simple docstring"""



 UpperCamelCase__       :     List[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       _a	(					SCREAMING_SNAKE_CASE						:					int     ,			SCREAMING_SNAKE_CASE						:					Tuple  ):







 """simple docstring"""



 UpperCamelCase__       :     Tuple 							= pt_weights["""visual.proj"""].data.T

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

 # copy embeddings
 UpperCamelCase__       :     str 							= pt_weights["""visual.conv1.weight"""].data
 UpperCamelCase__       :     List[str] 							= pt_weights["""visual.class_embedding"""].data
 UpperCamelCase__       :     Dict 							= pt_weights["""visual.positional_embedding"""].data

 # copy encoder
 copy_layers(hf_model.vision_model.encoder.layers     ,			_a     ,			'''visual.transformer.resblocks'''  )

@torch.no_grad()
def       _a	(					SCREAMING_SNAKE_CASE						:					Any     ,			SCREAMING_SNAKE_CASE						:					Dict     ,			SCREAMING_SNAKE_CASE						:					Optional[int]=None  ):







 """simple docstring"""



 assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
 UpperCamelCase__       :     Optional[int] 							= ChineseCLIPConfig.from_pretrained(_a  )

 UpperCamelCase__       :     str 							= ChineseCLIPModel(_a  ).eval()

 UpperCamelCase__       :     Optional[Any] 							= torch.load(_a     ,			map_location='''cpu'''  )["""state_dict"""]
 UpperCamelCase__       :     List[Any] 							= {(name[7:] if name.startswith('''module.'''  ) else name): value for name, value in pt_weights.items()}

 copy_text_model_and_projection(_a     ,			_a  )
 copy_vision_model_and_projection(_a     ,			_a  )
 UpperCamelCase__       :     Optional[Any] 							= pt_weights["""logit_scale"""].data

 hf_model.save_pretrained(_a  )


if __name__ == "__main__":
       __UpperCamelCase							:							Optional[Any]    							=					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."
       )
       __UpperCamelCase							:							str    							=					parser.parse_args()

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







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCamelCase_									=   logging.get_logger(__name__)







class       _snake_case				(     __snake_case ):






   '''simple docstring'''






   A__      : Optional[Any]       =						["pixel_values"]


   def __init__(    self:     Optional[Any]  ,lowerCamelCase_:     bool = True  ,lowerCamelCase_:     Optional[Dict[str, int]] = None  ,lowerCamelCase_:     PILImageResampling = PILImageResampling.BILINEAR  ,lowerCamelCase_:     bool = True  ,lowerCamelCase_:     Union[int, float] = 1 / 255  ,lowerCamelCase_:     bool = True  ,lowerCamelCase_:     Optional[Union[float, List[float]]] = None  ,lowerCamelCase_:     Optional[Union[float, List[float]]] = None  ,**lowerCamelCase_:     Dict  ,)	->      None:
       super().__init__(**lowerCamelCase_							)
       UpperCAmelCase_     :       Optional[Any]  		=					size if size is not None else {"""height""": 224, """width""": 224}
       UpperCAmelCase_     :       str  		=					get_size_dict(lowerCamelCase_							)
       UpperCAmelCase_     :       Tuple  		=					do_resize
       UpperCAmelCase_     :       Optional[Any]  		=					do_rescale
       UpperCAmelCase_     :       Optional[Any]  		=					do_normalize
       UpperCAmelCase_     :       int  		=					size
       UpperCAmelCase_     :       List[Any]  		=					resample
       UpperCAmelCase_     :       Optional[Any]  		=					rescale_factor
       UpperCAmelCase_     :       Dict  		=					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       UpperCAmelCase_     :       Any  		=					image_std if image_std is not None else IMAGENET_STANDARD_STD


   def       A__    (    self:     Union[str, Any]  ,lowerCamelCase_:     np.ndarray  ,lowerCamelCase_:     Dict[str, int]  ,lowerCamelCase_:     PILImageResampling = PILImageResampling.BILINEAR  ,lowerCamelCase_:     Optional[Union[str, ChannelDimension]] = None  ,**lowerCamelCase_:     Optional[int]  ,)	->      np.ndarray:
       UpperCAmelCase_     :       Dict  		=					get_size_dict(lowerCamelCase_							)
       if "height" not in size or "width" not in size:
           raise ValueError(F'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'''							)
       return resize(
           lowerCamelCase_  ,size=(size["""height"""], size["""width"""])  ,resample=lowerCamelCase_  ,data_format=lowerCamelCase_  ,**lowerCamelCase_							)


   def       A__    (    self:     List[str]  ,lowerCamelCase_:     np.ndarray  ,lowerCamelCase_:     float  ,lowerCamelCase_:     Optional[Union[str, ChannelDimension]] = None  ,**lowerCamelCase_:     List[Any]							)	->      np.ndarray:
       return rescale(lowerCamelCase_  ,scale=lowerCamelCase_  ,data_format=lowerCamelCase_  ,**lowerCamelCase_							)


   def       A__    (    self:     Optional[int]  ,lowerCamelCase_:     np.ndarray  ,lowerCamelCase_:     Union[float, List[float]]  ,lowerCamelCase_:     Union[float, List[float]]  ,lowerCamelCase_:     Optional[Union[str, ChannelDimension]] = None  ,**lowerCamelCase_:     List[Any]  ,)	->      np.ndarray:
       return normalize(lowerCamelCase_  ,mean=lowerCamelCase_  ,std=lowerCamelCase_  ,data_format=lowerCamelCase_  ,**lowerCamelCase_							)






   def       A__    (    self:     Optional[int]  ,lowerCamelCase_:     ImageInput  ,lowerCamelCase_:     Optional[bool] = None  ,lowerCamelCase_:     Dict[str, int] = None  ,lowerCamelCase_:     PILImageResampling = None  ,lowerCamelCase_:     Optional[bool] = None  ,lowerCamelCase_:     Optional[float] = None  ,lowerCamelCase_:     Optional[bool] = None  ,lowerCamelCase_:     Optional[Union[float, List[float]]] = None  ,lowerCamelCase_:     Optional[Union[float, List[float]]] = None  ,lowerCamelCase_:     Optional[Union[str, TensorType]] = None  ,lowerCamelCase_:     Union[str, ChannelDimension] = ChannelDimension.FIRST  ,**lowerCamelCase_:     int  ,)	->      List[Any]:
       UpperCAmelCase_     :       str  		=					do_resize if do_resize is not None else self.do_resize
       UpperCAmelCase_     :       Dict  		=					do_rescale if do_rescale is not None else self.do_rescale
       UpperCAmelCase_     :       Dict  		=					do_normalize if do_normalize is not None else self.do_normalize
       UpperCAmelCase_     :       int  		=					resample if resample is not None else self.resample
       UpperCAmelCase_     :       str  		=					rescale_factor if rescale_factor is not None else self.rescale_factor
       UpperCAmelCase_     :       Dict  		=					image_mean if image_mean is not None else self.image_mean
       UpperCAmelCase_     :       int  		=					image_std if image_std is not None else self.image_std

       UpperCAmelCase_     :       Tuple  		=					size if size is not None else self.size
       UpperCAmelCase_     :       Union[str, Any]  		=					get_size_dict(lowerCamelCase_							)

       UpperCAmelCase_     :       Optional[int]  		=					make_list_of_images(lowerCamelCase_							)

       if not valid_images(lowerCamelCase_							):
           raise ValueError(
               """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
               """torch.Tensor, tf.Tensor or jax.ndarray."""							)

       if do_resize and size is None:
           raise ValueError("""Size must be specified if do_resize is True."""							)

       if do_rescale and rescale_factor is None:
           raise ValueError("""Rescale factor must be specified if do_rescale is True."""							)

       # All transformations expect numpy arrays.
       UpperCAmelCase_     :       Optional[Any]  		=					[to_numpy_array(lowerCamelCase_							) for image in images]

       if do_resize:
           UpperCAmelCase_     :       int  		=					[self.resize(image=lowerCamelCase_  ,size=lowerCamelCase_  ,resample=lowerCamelCase_							) for image in images]

       if do_rescale:
           UpperCAmelCase_     :       Optional[Any]  		=					[self.rescale(image=lowerCamelCase_  ,scale=lowerCamelCase_							) for image in images]

       if do_normalize:
           UpperCAmelCase_     :       str  		=					[self.normalize(image=lowerCamelCase_  ,mean=lowerCamelCase_  ,std=lowerCamelCase_							) for image in images]

       UpperCAmelCase_     :       Any  		=					[to_channel_dimension_format(lowerCamelCase_  ,lowerCamelCase_							) for image in images]

       UpperCAmelCase_     :       List[str]  		=					{"""pixel_values""": images}
       return BatchFeature(data=lowerCamelCase_  ,tensor_type=lowerCamelCase_							)
