



import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel







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



    '''simple docstring'''




    UpperCAmelCase_		, UpperCAmelCase_		, UpperCAmelCase_     :       List[Any]  		=					pt_weights[F'''{prefix}.in_proj_weight'''].chunk(3   ,		dim=0    )
    UpperCAmelCase_		, UpperCAmelCase_		, 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       lowerCamelCase_  (    _a       :						Dict   ,		_a       :						Optional[int]   ,		_a       :						Tuple    ):



    '''simple docstring'''




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







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



    '''simple docstring'''




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







def       lowerCamelCase_  (    _a       :						Union[str, Any]   ,		_a       :						Union[str, Any]   ,		_a       :						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       lowerCamelCase_  (    _a       :						Any   ,		_a       :						Union[str, Any]   ,		_a       :						Union[str, Any]    ):



    '''simple docstring'''




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







def       lowerCamelCase_  (    _a       :						Tuple   ,		_a       :						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       lowerCamelCase_  (    _a       :						int   ,		_a       :						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       lowerCamelCase_  (    _a       :						Any   ,		_a       :						Dict   ,		_a       :						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_									=   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_									=   parser.parse_args()

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





import math







def       lowerCamelCase_  (    _a       :						int    ):



    '''simple docstring'''




    if 1 < number < 4:
        # 2 and 3 are primes
        return True
    elif number < 2 or number % 2 == 0 or number % 3 == 0:
        # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
        return False

    # All primes number are in format of 6k +/- 1
    for i in range(5   ,		int(math.sqrt(_a    ) + 1    )   ,		6    ):
        if number % i == 0 or number % (i + 2) == 0:
            return False
    return True







def       lowerCamelCase_  (    _a       :						int = 6008_5147_5143    ):



    '''simple docstring'''




    try:
        UpperCAmelCase_     :       str  		=					int(_a    )
    except (TypeError, ValueError):
        raise TypeError("""Parameter n must be int or castable to int."""    )
    if n <= 0:
        raise ValueError("""Parameter n must be greater than or equal to one."""    )
    UpperCAmelCase_     :       Optional[int]  		=					0
    if is_prime(_a    ):
        return n
    while n % 2 == 0:
        n //= 2
    if is_prime(_a    ):
        return n
    for i in range(3   ,		int(math.sqrt(_a    )    ) + 1   ,		2    ):
        if n % i == 0:
            if is_prime(n // i    ):
                UpperCAmelCase_     :       Optional[int]  		=					n // i
                break
            elif is_prime(_a    ):
                UpperCAmelCase_     :       str  		=					i
    return max_number


if __name__ == "__main__":
      print(F"{solution() = }")
