





"""simple docstring"""




import numpy as np

import datasets


SCREAMING_SNAKE_CASE_						       =	"""
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
"""

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

SCREAMING_SNAKE_CASE_						       =	"""
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {'mahalanobis': array([0.5])}
"""

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



     '''simple docstring'''

     def     SCREAMING_SNAKE_CASE__  (							self						:   Dict	)					->		Union[str, Any]:




           '''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     SCREAMING_SNAKE_CASE__  (							self						:   Tuple						,lowerCamelCase__						:   Union[str, Any]						,lowerCamelCase__						:   Tuple	)					->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						np.array(lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						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
           SCREAMING_SNAKE_CASE		=						X - np.mean(lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						np.cov(reference_distribution.T	)
           try:
                 SCREAMING_SNAKE_CASE		=						np.linalg.inv(lowerCamelCase__	)
           except np.linalg.LinAlgError:
                 SCREAMING_SNAKE_CASE		=						np.linalg.pinv(lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						np.dot(lowerCamelCase__						,lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						np.dot(lowerCamelCase__						,X_minus_mu.T	).diagonal()

           return {"mahalanobis": mahal_dist}









import unittest
from dataclasses import dataclass

import pytest

from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict

@dataclass
class 		UpperCamelCase__			(				lowerCAmelCase_       ):



     '''simple docstring'''

     __snake_case   :     int		     =      ComputeEnvironment.AMAZON_SAGEMAKER
     __snake_case   :     List[Any]		     =      True
     __snake_case   :     Optional[int]		     =      "ml.p3.2xlarge"
     __snake_case   :     List[str]		     =      "accelerate_sagemaker_execution_role"
     __snake_case   :     Tuple		     =      "hf-sm"
     __snake_case   :     Any		     =      "us-east-1"
     __snake_case   :     Union[str, Any]		     =      1
     __snake_case   :     Dict		     =      "accelerate-sagemaker-1"
     __snake_case   :     Tuple		     =      "1.6"
     __snake_case   :     List[str]		     =      "4.4"
     __snake_case   :     str		     =      "train.py"
     __snake_case   :     List[str]		     =      [
         "--model_name_or_path",
         "bert",
         "--do_train",
         "False",
         "--epochs",
         "3",
         "--learning_rate",
         "5e-5",
         "--max_steps",
         "50.5",
     ]
     __snake_case   :     Optional[int]		     =      [
         "--model_name_or_path",
         "bert",
         "--do_train",
         "--do_test",
         "False",
         "--do_predict",
         "--epochs",
         "3",
         "--learning_rate",
         "5e-5",
         "--max_steps",
         "50.5",
     ]

class 		UpperCamelCase__			(				unittest.TestCase       ):



     '''simple docstring'''

     def     SCREAMING_SNAKE_CASE__  (							self						:   Union[str, Any]	)					->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						_convert_nargs_to_dict(MockLaunchConfig.success_training_script_args	)
           assert isinstance(converted_args["""model_name_or_path"""]						,lowerCamelCase__	)
           assert isinstance(converted_args["""do_train"""]						,lowerCamelCase__	)
           assert isinstance(converted_args["""epochs"""]						,lowerCamelCase__	)
           assert isinstance(converted_args["""learning_rate"""]						,lowerCamelCase__	)
           assert isinstance(converted_args["""max_steps"""]						,lowerCamelCase__	)

           with pytest.raises(lowerCamelCase__	):
                 _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args	)


