






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A__      :     Optional[Any]       =					logging.get_logger(__name__)

A__      :     str       =					{
    'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json',
}
class  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				lowercase__											=			"""git_vision_model"""




				def __init__(	self		:       Any,    lowerCamelCase		:       Tuple=768,    lowerCamelCase		:       List[Any]=3_072,    lowerCamelCase		:       int=12,    lowerCamelCase		:       Optional[int]=12,    lowerCamelCase		:       List[Any]=3,    lowerCamelCase		:       List[Any]=224,    lowerCamelCase		:       Union[str, Any]=16,    lowerCamelCase		:       List[str]="quick_gelu",    lowerCamelCase		:       int=1E-5,    lowerCamelCase		:       Optional[int]=0.0,    lowerCamelCase		:       List[Any]=0.02,    **lowerCamelCase		:       Dict,    ):

								'''simple docstring'''
								super().__init__(**lowerCamelCase    )

								lowercase__  					=     hidden_size
								lowercase__  					=     intermediate_size
								lowercase__  					=     num_hidden_layers
								lowercase__  					=     num_attention_heads
								lowercase__  					=     num_channels
								lowercase__  					=     patch_size
								lowercase__  					=     image_size
								lowercase__  					=     initializer_range
								lowercase__  					=     attention_dropout
								lowercase__  					=     layer_norm_eps
								lowercase__  					=     hidden_act




				@classmethod
				def 							lowercase__  (	cls		:       Tuple,    lowerCamelCase		:       Union[str, os.PathLike],    **lowerCamelCase		:       Any    ):

								'''simple docstring'''
								cls._set_token_in_kwargs(lowerCamelCase    )

								lowercase__					,		lowercase__  					=     cls.get_config_dict(lowerCamelCase,    **lowerCamelCase    )

								# get the vision config dict if we are loading from GITConfig
								if config_dict.get('''model_type'''    ) == "git":
												lowercase__  					=     config_dict['''vision_config''']

								if "model_type" in config_dict and hasattr(cls,    '''model_type'''    ) and config_dict["model_type"] != cls.model_type:
												logger.warning(
												    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
												    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""    )

								return cls.from_dict(lowerCamelCase,    **lowerCamelCase    )



class  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				lowercase__											=			"""git"""




				def __init__(	self		:       str,    lowerCamelCase		:       Any=None,    lowerCamelCase		:       Any=30_522,    lowerCamelCase		:       Tuple=768,    lowerCamelCase		:       int=6,    lowerCamelCase		:       List[Any]=12,    lowerCamelCase		:       List[str]=3_072,    lowerCamelCase		:       Dict="gelu",    lowerCamelCase		:       Optional[Any]=0.1,    lowerCamelCase		:       Tuple=0.1,    lowerCamelCase		:       int=1_024,    lowerCamelCase		:       str=0.02,    lowerCamelCase		:       Union[str, Any]=1E-12,    lowerCamelCase		:       List[Any]=0,    lowerCamelCase		:       Any="absolute",    lowerCamelCase		:       Dict=True,    lowerCamelCase		:       Tuple=False,    lowerCamelCase		:       List[str]=101,    lowerCamelCase		:       List[Any]=102,    lowerCamelCase		:       List[Any]=None,    **lowerCamelCase		:       Dict,    ):

								'''simple docstring'''
								super().__init__(bos_token_id=lowerCamelCase,    eos_token_id=lowerCamelCase,    pad_token_id=lowerCamelCase,    **lowerCamelCase    )

								if vision_config is None:
												lowercase__  					=     {}
												logger.info('''vision_config is None. initializing the GitVisionConfig with default values.'''    )

								lowercase__  					=     GitVisionConfig(**lowerCamelCase    )
								lowercase__  					=     vocab_size
								lowercase__  					=     hidden_size
								lowercase__  					=     num_hidden_layers
								lowercase__  					=     num_attention_heads
								lowercase__  					=     hidden_act
								lowercase__  					=     intermediate_size
								lowercase__  					=     hidden_dropout_prob
								lowercase__  					=     attention_probs_dropout_prob
								lowercase__  					=     max_position_embeddings
								lowercase__  					=     initializer_range
								lowercase__  					=     layer_norm_eps
								lowercase__  					=     position_embedding_type
								lowercase__  					=     use_cache
								lowercase__  					=     tie_word_embeddings
								lowercase__  					=     num_image_with_embedding

								lowercase__  					=     bos_token_id
								lowercase__  					=     eos_token_id




				def 							lowercase__  (	self		:       Optional[int]    ):

								'''simple docstring'''
								lowercase__  					=     copy.deepcopy(self.__dict__    )
								lowercase__  					=     self.vision_config.to_dict()
								lowercase__  					=     self.__class__.model_type
								return output












import numpy as np

import datasets


A__      :     int       =					'\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n'

A__      :     Optional[int]       =					'\\n@article{de2000mahalanobis,\n  title={The mahalanobis distance},\n  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n  journal={Chemometrics and intelligent laboratory systems},\n  volume={50},\n  number={1},\n  pages={1--18},\n  year={2000},\n  publisher={Elsevier}\n}\n'

A__      :     Optional[int]       =					'\nArgs:\n    X: List of datapoints to be compared with the `reference_distribution`.\n    reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n    mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n    >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n    >>> print(results)\n    {\'mahalanobis\': array([0.5])}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,_KWARGS_DESCRIPTION      )
class  _UpperCAmelCase   (			datasets.Metric      ):

				"""simple docstring"""




				def 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								return datasets.MetricInfo(
								    description=_DESCRIPTION,    citation=_CITATION,    inputs_description=_KWARGS_DESCRIPTION,    features=datasets.Features(
								        {
								            '''X''': datasets.Sequence(datasets.Value('''float''',    id='''sequence'''    ),    id='''X'''    ),
								        }    ),    )




				def 							lowercase__  (	self		:       Dict,    lowerCamelCase		:       int,    lowerCamelCase		:       Optional[int]    ):

								'''simple docstring'''
								# convert to numpy arrays
								lowercase__  					=     np.array(lowerCamelCase    )
								lowercase__  					=     np.array(lowerCamelCase    )

								# Assert that arrays are 2D
								if len(X.shape    ) != 2:
												raise ValueError('''Expected `X` to be a 2D vector'''    )
								if len(reference_distribution.shape    ) != 2:
												raise ValueError('''Expected `reference_distribution` to be a 2D vector'''    )
								if reference_distribution.shape[0] < 2:
												raise ValueError(
												    '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension'''    )

								# Get mahalanobis distance for each prediction
								lowercase__  					=     X - np.mean(lowerCamelCase    )
								lowercase__  					=     np.cov(reference_distribution.T    )
								try:
												lowercase__  					=     np.linalg.inv(lowerCamelCase    )
								except np.linalg.LinAlgError:
												lowercase__  					=     np.linalg.pinv(lowerCamelCase    )
								lowercase__  					=     np.dot(lowerCamelCase,    lowerCamelCase    )
								lowercase__  					=     np.dot(lowerCamelCase,    X_minus_mu.T    ).diagonal()

								return {"mahalanobis": mahal_dist}




