
"""simple docstring"""





import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class     _UpperCAmelCase(    lowerCamelCase      ,     unittest.TestCase	):
		lowercase__						=      DDIMPipeline
		lowercase__						=      UNCONDITIONAL_IMAGE_GENERATION_PARAMS
		lowercase__						=      PipelineTesterMixin.required_optional_params - {
		    'num_images_per_prompt',
		    'latents',
		    'callback',
		    'callback_steps',
		}
		lowercase__						=      UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
		lowercase__						=      False



		def 						UpperCAmelCase							(					self)       ->       Optional[int]:






							'''simple docstring'''
							torch.manual_seed(0)
							_UpperCamelCase							 =  UNetaDModel(
							    block_out_channels=(32, 64)				,		layers_per_block=2				,		sample_size=32				,		in_channels=3				,		out_channels=3				,		down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')				,		up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')				,		)
							_UpperCamelCase							 =  DDIMScheduler()
							_UpperCamelCase							 =  {'''unet''': unet, '''scheduler''': scheduler}
							return components



		def 						UpperCAmelCase							(					self				,		__a				,		__a=0)       ->       Any:






							'''simple docstring'''
							if str(__a).startswith('''mps'''):
												_UpperCamelCase							 =  torch.manual_seed(__a)
							else:
												_UpperCamelCase							 =  torch.Generator(device=__a).manual_seed(__a)
							_UpperCamelCase							 =  {
							    '''batch_size''': 1,
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''output_type''': '''numpy''',
							}
							return inputs



		def 						UpperCAmelCase							(					self)       ->       Optional[int]:






							'''simple docstring'''
							_UpperCamelCase							 =  '''cpu'''

							_UpperCamelCase							 =  self.get_dummy_components()
							_UpperCamelCase							 =  self.pipeline_class(**__a)
							pipe.to(__a)
							pipe.set_progress_bar_config(disable=__a)

							_UpperCamelCase							 =  self.get_dummy_inputs(__a)
							_UpperCamelCase							 =  pipe(**__a).images
							_UpperCamelCase							 =  image[0, -3:, -3:, -1]

							self.assertEqual(image.shape				,		(1, 32, 32, 3))
							_UpperCamelCase							 =  np.array(
							    [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04])
							_UpperCamelCase							 =  np.abs(image_slice.flatten() - expected_slice).max()
							self.assertLessEqual(__a				,		1e-3)



		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3)



		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							super().test_save_load_local(expected_max_difference=3e-3)



		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''simple docstring'''
							super().test_save_load_optional_components(expected_max_difference=3e-3)




		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							super().test_inference_batch_single_identical(expected_max_diff=3e-3)






@slow
@require_torch_gpu
class     _UpperCAmelCase(    unittest.TestCase	):



		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase							 =  '''google/ddpm-cifar10-32'''

							_UpperCamelCase							 =  UNetaDModel.from_pretrained(__a)
							_UpperCamelCase							 =  DDIMScheduler()

							_UpperCamelCase							 =  DDIMPipeline(unet=__a				,		scheduler=__a)
							ddim.to(__a)
							ddim.set_progress_bar_config(disable=__a)

							_UpperCamelCase							 =  torch.manual_seed(0)
							_UpperCamelCase							 =  ddim(generator=__a				,		eta=0.0				,		output_type='''numpy''').images

							_UpperCamelCase							 =  image[0, -3:, -3:, -1]

							assert image.shape == (1, 32, 32, 3)
							_UpperCamelCase							 =  np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453])

							assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2




		def 						UpperCAmelCase							(					self)       ->       Any:






							'''simple docstring'''
							_UpperCamelCase							 =  '''google/ddpm-ema-bedroom-256'''

							_UpperCamelCase							 =  UNetaDModel.from_pretrained(__a)
							_UpperCamelCase							 =  DDIMScheduler.from_pretrained(__a)

							_UpperCamelCase							 =  DDIMPipeline(unet=__a				,		scheduler=__a)
							ddpm.to(__a)
							ddpm.set_progress_bar_config(disable=__a)

							_UpperCamelCase							 =  torch.manual_seed(0)
							_UpperCamelCase							 =  ddpm(generator=__a				,		output_type='''numpy''').images

							_UpperCamelCase							 =  image[0, -3:, -3:, -1]

							assert image.shape == (1, 2_56, 2_56, 3)
							_UpperCamelCase							 =  np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069])

							assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2








"""simple docstring"""





import datasets


_a														=		"""\
@InProceedings{conneau2018xnli,
  author = \"Conneau, Alexis
                 and Rinott, Ruty
                 and Lample, Guillaume
                 and Williams, Adina
                 and Bowman, Samuel R.
                 and Schwenk, Holger
                 and Stoyanov, Veselin\",
  title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",
  booktitle = \"Proceedings of the 2018 Conference on Empirical Methods
               in Natural Language Processing\",
  year = \"2018\",
  publisher = \"Association for Computational Linguistics\",
  location = \"Brussels, Belgium\",
}
"""

_a														=		"""\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
"""

_a														=		"""
Computes XNLI score which is just simple accuracy.
Args:
    predictions: Predicted labels.
    references: Ground truth labels.
Returns:
    'accuracy': accuracy
Examples:

    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> xnli_metric = datasets.load_metric(\"xnli\")
    >>> results = xnli_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}
"""



def       lowerCamelCase__		(			__snake_case,     __snake_case	)							->		str:


					"""simple docstring"""





					return (preds == labels).mean()






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



		def 						UpperCAmelCase							(					self)       ->       Dict:






							'''simple docstring'''
							return datasets.MetricInfo(
							    description=_DESCRIPTION				,		citation=_CITATION				,		inputs_description=_KWARGS_DESCRIPTION				,		features=datasets.Features(
							        {
							            '''predictions''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32'''),
							            '''references''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32'''),
							        })				,		codebase_urls=[]				,		reference_urls=[]				,		format='''numpy'''				,		)




		def 						UpperCAmelCase							(					self				,		__a				,		__a)       ->       Dict:






							'''simple docstring'''
							return {"accuracy": simple_accuracy(__a				,		__a)}






