




"""simple docstring"""







import os
import tempfile
import unittest

import numpy as np

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


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

  from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline

@require_flax
class 				snake_case_			(					unittest.TestCase			):







   """simple docstring"""




   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       with tempfile.TemporaryDirectory() as tmpdirname:
           # pipeline has Flax weights
           UpperCamelCase              =	FlaxDiffusionPipeline.from_pretrained(
               '''hf-internal-testing/tiny-stable-diffusion-pipe'''       ,					safety_checker=lowerCamelCase_       ,					cache_dir=lowerCamelCase_)

           UpperCamelCase              =	[t[-1] for t in os.walk(os.path.join(lowerCamelCase_       ,					os.listdir(lowerCamelCase_)[0]       ,					'''snapshots'''))]
           UpperCamelCase              =	[item for sublist in all_root_files for item in sublist]

           # None of the downloaded files should be a PyTorch file even if we have some here:
           # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
           assert not any(f.endswith('''.bin''') for f in files)

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







   """simple docstring"""




   def   UpperCAmelCase__			(		self)				->   Any:
       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''hf-internal-testing/tiny-stable-diffusion-pipe'''       ,					safety_checker=lowerCamelCase_)

       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.random.PRNGKey(0)
       UpperCamelCase              =	4

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)

       # shard inputs and rng
       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	jax.random.split(lowerCamelCase_       ,					lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)

       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images

       assert images.shape == (num_samples, 1, 6_4, 6_4, 3)
       if jax.device_count() == 8:
           assert np.abs(np.abs(images[0, 0, :2, :2, -2:]       ,					dtype=np.floataa).sum() - 4.151_4745) < 1e-3
           assert np.abs(np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 4_9947.875) < 5e-1

       UpperCamelCase              =	pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
       assert len(lowerCamelCase_) == num_samples







   def   UpperCAmelCase__			(		self)				->   Tuple:
       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''flax'''       ,					safety_checker=lowerCamelCase_)

       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.random.PRNGKey(0)
       UpperCamelCase              =	5_0

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)

       # shard inputs and rng
       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	jax.random.split(lowerCamelCase_       ,					lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)

       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
           assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,					dtype=np.floataa).sum() - 0.0565_2401)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 238_3808.2)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   Any:
       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''bf16'''       ,					dtype=jnp.bfloataa       ,					safety_checker=lowerCamelCase_)

       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.random.PRNGKey(0)
       UpperCamelCase              =	5_0

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)

       # shard inputs and rng
       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	jax.random.split(lowerCamelCase_       ,					lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)

       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
           assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,					dtype=np.floataa).sum() - 0.0400_3906)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 237_3516.75)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   str:
       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''bf16'''       ,					dtype=jnp.bfloataa)

       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.random.PRNGKey(0)
       UpperCamelCase              =	5_0

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)

       # shard inputs and rng
       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	jax.random.split(lowerCamelCase_       ,					lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)

       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
           assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,					dtype=np.floataa).sum() - 0.0400_3906)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 237_3516.75)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   str:
       UpperCamelCase              =	FlaxDDIMScheduler(
           beta_start=0.0_0085       ,					beta_end=0.012       ,					beta_schedule='''scaled_linear'''       ,					set_alpha_to_one=lowerCamelCase_       ,					steps_offset=1       ,					)

       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''bf16'''       ,					dtype=jnp.bfloataa       ,					scheduler=lowerCamelCase_       ,					safety_checker=lowerCamelCase_       ,					)
       UpperCamelCase              =	scheduler.create_state()

       UpperCamelCase              =	scheduler_state

       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.random.PRNGKey(0)
       UpperCamelCase              =	5_0

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)

       # shard inputs and rng
       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	jax.random.split(lowerCamelCase_       ,					lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)

       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
           assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,					dtype=np.floataa).sum() - 0.0_4504_3945)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 234_7693.5)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   List[Any]:
       UpperCamelCase              =	(
           '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
           ''' field, close up, split lighting, cinematic'''
       )

       UpperCamelCase              =	jax.device_count()
       UpperCamelCase              =	num_samples * [prompt]
       UpperCamelCase              =	jax.random.split(jax.random.PRNGKey(0)       ,					lowerCamelCase_)

       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''bf16'''       ,					dtype=jnp.bfloataa       ,					safety_checker=lowerCamelCase_       ,					)

       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)
       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images
       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       UpperCamelCase              =	images[2, 0, 2_5_6, 1_0:1_7, 1]

       # With memory efficient attention
       UpperCamelCase       ,	UpperCamelCase              =	FlaxStableDiffusionPipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''       ,					revision='''bf16'''       ,					dtype=jnp.bfloataa       ,					safety_checker=lowerCamelCase_       ,					use_memory_efficient_attention=lowerCamelCase_       ,					)

       UpperCamelCase              =	replicate(lowerCamelCase_)
       UpperCamelCase              =	pipeline.prepare_inputs(lowerCamelCase_)
       UpperCamelCase              =	shard(lowerCamelCase_)
       UpperCamelCase              =	pipeline(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					jit=lowerCamelCase_).images
       assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       UpperCamelCase              =	images[2, 0, 2_5_6, 1_0:1_7, 1]

       # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
       # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
       assert abs(slice_eff - slice).max() < 1e-2






'''simple docstring'''






from sklearn.metrics import matthews_corrcoef

import datasets


__UpperCamelCase					    =	"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

__UpperCamelCase					    =	"\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

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




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

		def 	lowercase__     (   self					:   Tuple			)					->    Dict:


					"""simple docstring"""

					return datasets.MetricInfo(
					    description=_DESCRIPTION  ,      citation=_CITATION  ,      inputs_description=_KWARGS_DESCRIPTION  ,      features=datasets.Features(
					        {
					            """predictions""": datasets.Value("""int32"""			),
					            """references""": datasets.Value("""int32"""			),
					        }			)  ,      reference_urls=[
					        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"""
					    ]  ,      )

		def 	lowercase__     (   self					:   List[Any]  ,      __magic_name__					:   Tuple  ,      __magic_name__					:   List[Any]  ,      __magic_name__					:   Union[str, Any]=None			)					->    Optional[int]:


					"""simple docstring"""

					return {
					    "matthews_correlation": float(matthews_corrcoef(__magic_name__  ,      __magic_name__  ,      sample_weight=__magic_name__			)			),
					}


