






import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel


def 					UpperCAmelCase			(				a__    ,			a__    ,			a__   ):





						'''simple docstring'''






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

						lowerCAmelCase      :List[Any]				  = pt_weights[F"""{prefix}.out_proj.weight"""]
						lowerCAmelCase      :str				  = pt_weights[F"""{prefix}.out_proj.bias"""]

						lowerCAmelCase      :List[str]				  = q_proj
						lowerCAmelCase      :int				  = q_proj_bias

						lowerCAmelCase      :Optional[int]				  = k_proj
						lowerCAmelCase      :str				  = k_proj_bias

						lowerCAmelCase      :Optional[Any]				  = v_proj
						lowerCAmelCase      :Optional[int]				  = v_proj_bias

						lowerCAmelCase      :str				  = out_proj_weights
						lowerCAmelCase      :str				  = out_proj_bias


def 					UpperCAmelCase			(				a__    ,			a__    ,			a__   ):





						'''simple docstring'''






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


def 					UpperCAmelCase			(				a__    ,			a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Optional[int]				  = pt_weights[F"""{prefix}.weight"""].data
						lowerCAmelCase      :Any				  = pt_weights[F"""{prefix}.bias"""].data


def 					UpperCAmelCase			(				a__    ,			a__    ,			a__   ):





						'''simple docstring'''






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

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

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


def 					UpperCAmelCase			(				a__    ,			a__    ,			a__   ):





						'''simple docstring'''






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


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Tuple				  = pt_weights['text_projection'].data.T

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


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Optional[Any]				  = pt_weights['visual.proj'].data.T

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

						# copy embeddings
						lowerCAmelCase      :Optional[int]				  = pt_weights['visual.conv1.weight'].data
						lowerCAmelCase      :str				  = pt_weights['visual.class_embedding'].data
						lowerCAmelCase      :List[str]				  = pt_weights['visual.positional_embedding'].data

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


@torch.no_grad()
def 					UpperCAmelCase			(				a__    ,			a__    ,			a__=None   ):





						'''simple docstring'''






						assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
						lowerCAmelCase      :Union[str, Any]				  = ChineseCLIPConfig.from_pretrained(lowercase__   )

						lowerCAmelCase      :Union[str, Any]				  = ChineseCLIPModel(lowercase__   ).eval()

						lowerCAmelCase      :int				  = torch.load(lowercase__    ,			map_location='cpu'   )['state_dict']
						lowerCAmelCase      :Dict				  = {(name[7:] if name.startswith('module.'   ) else name): value for name, value in pt_weights.items()}

						copy_text_model_and_projection(lowercase__    ,			lowercase__   )
						copy_vision_model_and_projection(lowercase__    ,			lowercase__   )
						lowerCAmelCase      :Union[str, Any]				  = pt_weights['logit_scale'].data

						hf_model.save_pretrained(lowercase__   )


if __name__ == "__main__":
		__SCREAMING_SNAKE_CASE      =      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      =      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"""


from __future__ import annotations


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Union[str, Any]				  = [0] * len(a__   )
						for i in range(1    ,			len(a__   )   ):
												lowerCAmelCase      :Optional[int]				  = duration_times[i - 1] + waiting_times[i - 1]
						return waiting_times


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						return [
						    duration_time + waiting_times[i]
						    for i, duration_time in enumerate(a__   )
						]


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						return sum(a__   ) / len(a__   )


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						return sum(a__   ) / len(a__   )


if __name__ == "__main__":
		# process id's
		__SCREAMING_SNAKE_CASE      =      [1, 2, 3]

		# ensure that we actually have processes
		if len(processes) == 0:
				print('Zero amount of processes')
				raise SystemExit(0)

		# duration time of all processes
		__SCREAMING_SNAKE_CASE      =      [19, 8, 9]

		# ensure we can match each id to a duration time
		if len(duration_times) != len(processes):
				print('Unable to match all id\'s with their duration time')
				raise SystemExit(0)

		# get the waiting times and the turnaround times
		__SCREAMING_SNAKE_CASE      =      calculate_waiting_times(duration_times)
		__SCREAMING_SNAKE_CASE      =      calculate_turnaround_times(duration_times, waiting_times)

		# get the average times
		__SCREAMING_SNAKE_CASE      =      calculate_average_waiting_time(waiting_times)
		__SCREAMING_SNAKE_CASE      =      calculate_average_turnaround_time(turnaround_times)

		# print all the results
		print('Process ID\tDuration Time\tWaiting Time\tTurnaround Time')
		for i, process in enumerate(processes):
				print(
				    F"""{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t"""
				    F"""{turnaround_times[i]}"""
				)
		print(F"""Average waiting time = {average_waiting_time}""")
		print(F"""Average turn around time = {average_turnaround_time}""")