





import numpy as np

import datasets


_lowerCAmelCase							:					Dict		    =		'''
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/]
'''

_lowerCAmelCase							:					Union[str, Any]		    =		'''\
@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}
}
'''

_lowerCAmelCase							:					Any		    =		'''
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     __magic_name__     (							datasets.Metric							):





     """simple docstring"""



     def   SCREAMING_SNAKE_CASE						(							self				:List[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   SCREAMING_SNAKE_CASE						(							self				:Optional[int]	,					snake_case				:Optional[int]	,					snake_case				:int     ):





        '''simple docstring'''




        A_    : List[str]								=	np.array(UpperCamelCase_     )
        A_    : Optional[Any]								=	np.array(UpperCamelCase_     )

        # 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
        A_    : List[Any]								=	X - np.mean(UpperCamelCase_     )
        A_    : Union[str, Any]								=	np.cov(reference_distribution.T     )
        try:
           A_    : Dict								=	np.linalg.inv(UpperCamelCase_     )
        except np.linalg.LinAlgError:
           A_    : List[str]								=	np.linalg.pinv(UpperCamelCase_     )
        A_    : Optional[int]								=	np.dot(UpperCamelCase_	,					UpperCamelCase_     )
        A_    : Optional[Any]								=	np.dot(UpperCamelCase_	,					X_minus_mu.T     ).diagonal()

        return {"mahalanobis": mahal_dist}




"""simple docstring"""





import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
 import jax
 import jax.numpy as jnp
 from flax.jax_utils import replicate
 from flax.training.common_utils import shard



@slow
@require_flax
class 						snake_case_(				unittest.TestCase	):






     def    lowerCamelCase__   (		self     :    int ):
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           lowerCAmelCase,					lowerCAmelCase    :		Optional[int]				=      FlaxStableDiffusionPipeline.from_pretrained(
               '''stabilityai/stable-diffusion-2'''    , revision='''bf16'''    , dtype=jnp.bfloataa    , )

           lowerCAmelCase    :		Optional[int]				=      '''A painting of a squirrel eating a burger'''
           lowerCAmelCase    :		List[str]				=      jax.device_count()
           lowerCAmelCase    :		Optional[int]				=      num_samples * [prompt]
           lowerCAmelCase    :		Any				=      sd_pipe.prepare_inputs(UpperCamelCase_ )

           lowerCAmelCase    :		Optional[int]				=      replicate(UpperCamelCase_ )
           lowerCAmelCase    :		Union[str, Any]				=      shard(UpperCamelCase_ )

           lowerCAmelCase    :		Optional[int]				=      jax.random.PRNGKey(0 )
           lowerCAmelCase    :		Optional[Any]				=      jax.random.split(UpperCamelCase_    , jax.device_count() )

           lowerCAmelCase    :		str				=      sd_pipe(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , num_inference_steps=2_5    , jit=UpperCamelCase_ )[0]
           assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

           lowerCAmelCase    :		str				=      images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
           lowerCAmelCase    :		List[str]				=      images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

           lowerCAmelCase    :		Dict				=      jnp.asarray(jax.device_get(image_slice.flatten() ) )
           lowerCAmelCase    :		List[str]				=      jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] )
           print(F'''output_slice: {output_slice}''' )
           assert jnp.abs(output_slice - expected_slice ).max() < 1E-2






     def    lowerCamelCase__   (		self     :    Union[str, Any] ):
           lowerCAmelCase    :		Union[str, Any]				=      '''stabilityai/stable-diffusion-2'''
           lowerCAmelCase,					lowerCAmelCase    :		Dict				=      FlaxDPMSolverMultistepScheduler.from_pretrained(UpperCamelCase_    , subfolder='''scheduler''' )
           lowerCAmelCase,					lowerCAmelCase    :		int				=      FlaxStableDiffusionPipeline.from_pretrained(
               UpperCamelCase_    , scheduler=UpperCamelCase_    , revision='''bf16'''    , dtype=jnp.bfloataa    , )
           lowerCAmelCase    :		List[Any]				=      scheduler_params

           lowerCAmelCase    :		List[Any]				=      '''A painting of a squirrel eating a burger'''
           lowerCAmelCase    :		Any				=      jax.device_count()
           lowerCAmelCase    :		int				=      num_samples * [prompt]
           lowerCAmelCase    :		int				=      sd_pipe.prepare_inputs(UpperCamelCase_ )

           lowerCAmelCase    :		Dict				=      replicate(UpperCamelCase_ )
           lowerCAmelCase    :		Tuple				=      shard(UpperCamelCase_ )

           lowerCAmelCase    :		int				=      jax.random.PRNGKey(0 )
           lowerCAmelCase    :		Optional[int]				=      jax.random.split(UpperCamelCase_    , jax.device_count() )

           lowerCAmelCase    :		Tuple				=      sd_pipe(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , num_inference_steps=2_5    , jit=UpperCamelCase_ )[0]
           assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

           lowerCAmelCase    :		Any				=      images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
           lowerCAmelCase    :		str				=      images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

           lowerCAmelCase    :		Optional[int]				=      jnp.asarray(jax.device_get(image_slice.flatten() ) )
           lowerCAmelCase    :		Tuple				=      jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] )
           print(F'''output_slice: {output_slice}''' )
           assert jnp.abs(output_slice - expected_slice ).max() < 1E-2


