


'''simple docstring'''







import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     Optional[Any]   ,_UpperCAmelCase     :     Tuple   ,_UpperCAmelCase     :     List[Any]  )  ->      Any:
       _a ,   _a ,   _a   :			Optional[int]					 =pt_weights[F"{prefix}.in_proj_weight"].chunk(3   ,dim=0  )
       _a ,   _a ,   _a   :			List[Any]					 =pt_weights[F"{prefix}.in_proj_bias"].chunk(3   ,dim=0  )

       _a   :			Optional[Any]					 =pt_weights[F"{prefix}.out_proj.weight"]
       _a   :			Any					 =pt_weights[F"{prefix}.out_proj.bias"]

       _a   :			int					 =q_proj
       _a   :			Union[str, Any]					 =q_proj_bias

       _a   :			Tuple					 =k_proj
       _a   :			int					 =k_proj_bias

       _a   :			str					 =v_proj
       _a   :			Dict					 =v_proj_bias

       _a   :			int					 =out_proj_weights
       _a   :			Union[str, Any]					 =out_proj_bias


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     int   ,_UpperCAmelCase     :     Optional[int]   ,_UpperCAmelCase     :     List[str]  )  ->      Dict:
       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     :     str   ,_UpperCAmelCase     :     Optional[Any]   ,_UpperCAmelCase     :     Dict  )  ->      Optional[int]:
       _a   :			str					 =pt_weights[F"{prefix}.weight"].data
       _a   :			Optional[int]					 =pt_weights[F"{prefix}.bias"].data


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     List[Any]   ,_UpperCAmelCase     :     Optional[int]   ,_UpperCAmelCase     :     Tuple  )  ->      List[Any]:
       # 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     :     int   ,_UpperCAmelCase     :     Union[str, Any]   ,_UpperCAmelCase     :     Optional[Any]  )  ->      Dict:
       for layer_id, hf_layer in enumerate(_UpperCAmelCase  ):
              copy_layer(_UpperCAmelCase   ,_UpperCAmelCase   ,F"{prefix}.{layer_id}"  )


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     Any   ,_UpperCAmelCase     :     List[Any]  )  ->      List[str]:
       # copy projection
       _a   :			int					 =pt_weights["""text_projection"""].data.T

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


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     Tuple   ,_UpperCAmelCase     :     Dict  )  ->      Optional[int]:
       # copy projection
       _a   :			Optional[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
       _a   :			Any					 =pt_weights["""visual.conv1.weight"""].data
       _a   :			Dict					 =pt_weights["""visual.class_embedding"""].data
       _a   :			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      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     List[str]   ,_UpperCAmelCase     :     List[Any]   ,_UpperCAmelCase     :     str=None  )  ->      Dict:
       assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
       _a   :			List[str]					 =ChineseCLIPConfig.from_pretrained(_UpperCAmelCase  )

       _a   :			Dict					 =ChineseCLIPModel(_UpperCAmelCase  ).eval()

       _a   :			Optional[Any]					 =torch.load(_UpperCAmelCase   ,map_location="""cpu"""  )["""state_dict"""]
       _a   :			Dict					 ={(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  )
       _a   :			Union[str, Any]					 =pt_weights["""logit_scale"""].data

       hf_model.save_pretrained(_UpperCAmelCase  )


if __name__ == "__main__":
   A__:   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.'''
   )
   A__:   Optional[Any]    =	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 sklearn.metrics import mean_absolute_error

import datasets


A__:   Dict    =	'''\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
'''

A__:   Union[str, Any]    =	'''\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
'''


A__:   str    =	'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 "raw_values" : Returns a full set of errors in case of multioutput input.

                 "uniform_average" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is "raw_values", then mean absolute error is returned for each output separately. If multioutput is "uniform_average" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric("mae")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.5}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric("mae", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results)
    {\'mae\': array([0.5, 1. ])}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,					_KWARGS_DESCRIPTION				)
class A__	(						datasets.Metric				):






      def __UpperCAmelCase	(			self      :List[Any]     )	-> Dict:




             '''simple docstring'''
             return datasets.MetricInfo(
                 description=_DESCRIPTION					,						citation=_CITATION					,						inputs_description=_KWARGS_DESCRIPTION					,						features=datasets.Features(self._get_feature_types()     )					,						reference_urls=[
                     """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"""
                 ]					,						)






      def __UpperCAmelCase	(			self      :Dict     )	-> List[str]:




             '''simple docstring'''
             if self.config_name == "multilist":
                    return {
                        "predictions": datasets.Sequence(datasets.Value("""float"""     )     ),
                        "references": datasets.Sequence(datasets.Value("""float"""     )     ),
                    }
             else:
                    return {
                        "predictions": datasets.Value("""float"""     ),
                        "references": datasets.Value("""float"""     ),
                    }






      def __UpperCAmelCase	(			self      :Any					,						SCREAMING_SNAKE_CASE      :Union[str, Any]					,						SCREAMING_SNAKE_CASE      :str					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=None					,						SCREAMING_SNAKE_CASE      :Any="uniform_average"     )	-> List[Any]:




             '''simple docstring'''
             _a   :			Tuple					 =mean_absolute_error(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE					,						sample_weight=SCREAMING_SNAKE_CASE					,						multioutput=SCREAMING_SNAKE_CASE     )

             return {"mae": mae_score}


