



"""simple docstring"""







import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		_lowercase     ,  _lowercase     ,  _lowercase				: str     =   pt_weights[F"""{prefix}.in_proj_weight"""].chunk(3   ,				dim=0      )
		_lowercase     ,  _lowercase     ,  _lowercase				: Optional[Any]     =   pt_weights[F"""{prefix}.in_proj_bias"""].chunk(3   ,				dim=0      )

		_lowercase				: Optional[int]     =   pt_weights[F"""{prefix}.out_proj.weight"""]
		_lowercase				: Union[str, Any]     =   pt_weights[F"""{prefix}.out_proj.bias"""]

		_lowercase				: Union[str, Any]     =   q_proj
		_lowercase				: List[str]     =   q_proj_bias

		_lowercase				: Any     =   k_proj
		_lowercase				: int     =   k_proj_bias

		_lowercase				: int     =   v_proj
		_lowercase				: List[Any]     =   v_proj_bias

		_lowercase				: str     =   out_proj_weights
		_lowercase				: str     =   out_proj_bias


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		copy_linear(hf_mlp.fca   ,				__UpperCAmelCase   ,				F"""{prefix}.c_fc"""      )
		copy_linear(hf_mlp.fca   ,				__UpperCAmelCase   ,				F"""{prefix}.c_proj"""      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		_lowercase				: List[Any]     =   pt_weights[F"""{prefix}.weight"""].data
		_lowercase				: List[str]     =   pt_weights[F"""{prefix}.bias"""].data


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		# copy layer norms
		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  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		for layer_id, hf_layer in enumerate(__UpperCAmelCase      ):
				copy_layer(__UpperCAmelCase   ,				__UpperCAmelCase   ,				F"""{prefix}.{layer_id}"""      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase      ):
		# copy projection
		_lowercase				: List[str]     =   pt_weights["""text_projection"""].data.T

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


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase      ):
		# copy projection
		_lowercase				: Any     =   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
		_lowercase				: Optional[Any]     =   pt_weights["""visual.conv1.weight"""].data
		_lowercase				: List[Any]     =   pt_weights["""visual.class_embedding"""].data
		_lowercase				: Optional[Any]     =   pt_weights["""visual.positional_embedding"""].data

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


@torch.no_grad()
def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase=None      ):
		assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
		_lowercase				: int     =   ChineseCLIPConfig.from_pretrained(__UpperCAmelCase      )

		_lowercase				: Union[str, Any]     =   ChineseCLIPModel(__UpperCAmelCase      ).eval()

		_lowercase				: Optional[int]     =   torch.load(__UpperCAmelCase   ,				map_location="""cpu"""      )["""state_dict"""]
		_lowercase				: 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      )
		_lowercase				: int     =   pt_weights["""logit_scale"""].data

		hf_model.save_pretrained(__UpperCAmelCase      )


if __name__ == "__main__":
		UpperCAmelCase:  List[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:  Tuple			     =				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 os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


UpperCAmelCase:  Union[str, Any]			     =				namedtuple("""ExampleNamedTuple""", """a b c""")





class   UpperCamelCase	(     unittest.TestCase       ):




	"""simple docstring"""






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[Any]     =   torch.randn(5				,2   )
			_lowercase				: List[Any]     =   torch.device("""cuda"""   ) if torch.cuda.is_available() else torch.device("""cpu"""   )

			_lowercase				: int     =   send_to_device(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.cpu()				,UpperCAmelCase_   )   )

			_lowercase				: int     =   send_to_device((tensor, [tensor, tensor], 1)				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta[0].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta[1]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta[1][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta[1][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta[2]				,1   )

			_lowercase				: Any     =   send_to_device({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""a"""].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta["""b"""]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""b"""][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta["""b"""][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta["""c"""]				,1   )

			_lowercase				: Optional[int]     =   send_to_device(ExampleNamedTuple(a=UpperCAmelCase_				,b=[tensor, tensor]				,c=1   )				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.a.cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta.b				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta.b[0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta.b[1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta.c				,1   )

			_lowercase				: str     =   send_to_device(UserDict({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}   )				,UpperCAmelCase_   )
			self.assertIsInstance(UpperCAmelCase_				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""a"""].cpu()				,UpperCAmelCase_   )   )
			self.assertIsInstance(resulta["""b"""]				,UpperCAmelCase_   )
			self.assertTrue(torch.equal(resulta["""b"""][0].cpu()				,UpperCAmelCase_   )   )
			self.assertTrue(torch.equal(resulta["""b"""][1].cpu()				,UpperCAmelCase_   )   )
			self.assertEqual(resulta["""c"""]				,1   )






	def    lowerCamelCase__					(     self   ):
			with self.assertRaises(UpperCAmelCase_   ) as cm:
					_lowercase				: str     =   recursively_apply(torch.tensor				,(torch.tensor(1   ), 1)				,error_on_other_type=UpperCAmelCase_   )
			self.assertEqual(
			    str(cm.exception   )				,"""Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."""				,)






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[int]     =   torch.tensor([1, 2, 3, 4, 5]   )
			self.assertEqual(listify(UpperCAmelCase_   )				,[1, 2, 3, 4, 5]   )

			_lowercase				: Optional[int]     =   torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )
			self.assertEqual(listify(UpperCAmelCase_   )				,[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )

			_lowercase				: Optional[Any]     =   torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )
			self.assertEqual(
			    listify(UpperCAmelCase_   )				,[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )






	def    lowerCamelCase__					(     self   ):
			with patch_environment(aa=1				,BB=2   ):
					self.assertEqual(os.environ.get("""AA"""   )				,"""1"""   )
					self.assertEqual(os.environ.get("""BB"""   )				,"""2"""   )

			self.assertNotIn("""AA"""				,os.environ   )
			self.assertNotIn("""BB"""				,os.environ   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[Any]     =   RegressionModel()
			_lowercase				: List[Any]     =   model.forward
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Any     =   extract_model_from_parallel(UpperCAmelCase_				,keep_fpaa_wrapper=UpperCAmelCase_   )
			_lowercase				: Tuple     =   pickle.dumps(UpperCAmelCase_   )






	@require_cuda
	def    lowerCamelCase__					(     self   ):
			_lowercase				: str     =   RegressionModel()
			_lowercase				: Any     =   model.forward
			_lowercase				: Any     =   torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Any     =   extract_model_from_parallel(UpperCAmelCase_				,keep_fpaa_wrapper=UpperCAmelCase_   )
			_lowercase				: Tuple     =   pickle.dumps(UpperCAmelCase_   )






	@require_cuda
	@require_torch_min_version(version="""2.0"""   )
	def    lowerCamelCase__					(     self   ):
			_lowercase				: str     =   RegressionModel()
			_lowercase				: Any     =   model.forward
			_lowercase				: Union[str, Any]     =   torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			_lowercase				: Optional[Any]     =   convert_outputs_to_fpaa(model.forward   )
			_lowercase				: Union[str, Any]     =   torch.compile(model.forward				,backend="""inductor"""   )
			_lowercase				: Any     =   torch.randn(4				,10   ).cuda()
			_lowercase				: int     =   model(UpperCAmelCase_   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[str]     =   RegressionModel()
			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			_lowercase				: Any     =   torch.nn.parallel.DataParallel(UpperCAmelCase_   )
			_lowercase				: List[Any]     =   extract_model_from_parallel(UpperCAmelCase_   )

			self.assertEqual(UpperCAmelCase_				,UpperCAmelCase_   )






	@require_torch_min_version(version="""2.0"""   )
	def    lowerCamelCase__					(     self   ):
			_lowercase				: int     =   RegressionModel()
			_lowercase				: List[str]     =   torch.compile(UpperCAmelCase_   )

			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			_lowercase				: Optional[int]     =   torch.nn.parallel.DataParallel(UpperCAmelCase_   )
			_lowercase				: int     =   torch.compile(UpperCAmelCase_   )
			_lowercase				: Dict     =   extract_model_from_parallel(UpperCAmelCase_   )

			self.assertEqual(compiled_model._orig_mod				,compiled_model_unwrapped._orig_mod   )






	def    lowerCamelCase__					(     self   ):
			self.assertEqual(find_device([1, """a""", torch.tensor([1, 2, 3]   )]   )				,torch.device("""cpu"""   )   )
			self.assertEqual(find_device({"""a""": 1, """b""": torch.tensor([1, 2, 3]   )}   )				,torch.device("""cpu"""   )   )
			self.assertIsNone(find_device([1, """a"""]   )   )



